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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s