Generating a string which isn’t a property name of a given object
Helping out with the test262 test suite (official ECMAScript 5 test suite), I have come to a problem. Based on a given object, find/generate a string which isn’t a property name of the object.
Here is the solution I’ve come up with
function unusedPropertyName(o){
var ownPropNames = Object.getOwnPropertyNames(o);
var unusedName = ownPropNames.reduce(function(prev, curr, i){
var A = ‘a’, B = ‘b’;
var l = curr[i];
l = (l=== undefined || l !== A) ? A : B;
return prev + l;
}, ”);
return unusedName;
}
The idea is to list all property names. Then, create a string which has one letter that differs from each property name. This idea is inpired by Cantor’s diagonal argument.
I found it was an interesting use of Array.prototype.reduce and was worth sharing.
on
2011-02-28
by