Skip to content Skip to sidebar Skip to footer

Unique Id Or Object Signature

I am working on a Logging system, and am looking forward to implement a log once method. What I'm stuck with, is, how would I retrieve unique identifier and/or objects signature, t

Solution 1:

You can use JSON.stringify to get a "signature" of arbitrary values. Of course this does not save object types, and does not work for Date or Function instances; also it does not distinguish between different objects with the same values. If you want that, you will need to store a explicit reference to them (of course hindering the garbage collector from freeing them):

var loggedVals = [];
console.once = function() {
    var args = [].slice.call(arguments).filter(function(arg) {
        return (loggedVals.lastIndexOf(arg)==-1) && loggedVals.push(arg);
    });
    if (args.length)
        console.log.apply(console, args);
});

If you don't want to store references to them, you will need to tag them as "logged" by adding a hidden property (just like a UID generator would do it):

function(arg) {
        return !arg.__hasbeenlogged__ && 
          Object.defineProperty(arg, "__hasbeenlogged__", {value: true});
          // configurable, enumarable and writable are implicitly false
    } …

Notice that this solution does not work for primitive values and even fails for null and undefined - you might need to mix the two approaches.

Post a Comment for "Unique Id Or Object Signature"