Created
February 15, 2009 06:00
-
-
Save javascripter/64615 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getObjectId = function () { | |
var nums = {}, strs = {}; | |
var numid = 0, strid = 0, objid = 0; | |
var has = Object.prototype.hasOwnProperty; | |
return function (object) { | |
switch (typeof object) { | |
case "object":case "function": | |
if (object === null) return 0; | |
if (has.call(object, "__id")) return object.__id; | |
return object.__id = objid++ * 3 + 4; | |
case "number": | |
if (has.call(nums, object)) return nums[object]; | |
return nums[object] = numid++ * 3 + 5; | |
case "string": | |
if (has.call(strs, object)) return strs[object]; | |
return strs[object] = strid++ * 3 + 6; | |
case "undefined": | |
return 1; | |
case "boolean": | |
return object? 2: 3; | |
default: | |
throw new Error("unsupported type: " + typeof object); | |
} | |
}; | |
}(); | |
(function () { | |
function error() { | |
console.error.apply(console, arguments); | |
} | |
function eq() { | |
var iseq = Array.reduce(arguments, function (a, b) {return a === b;}); | |
if (!iseq) error("not equal:", arguments); | |
} | |
function ne() { | |
var isne = Array.reduce(arguments, function (a, b) {return a !== b;}); | |
if (!isne) error("equal:", arguments); | |
} | |
var a = getObjectId(0); | |
var b = getObjectId(1); | |
var c = getObjectId("a"); | |
var d = getObjectId(""); | |
var e = getObjectId("hasOwnProperty"); | |
var f = getObjectId(null); | |
var g = getObjectId(undefined); | |
var h = getObjectId(true); | |
var i = getObjectId(false); | |
var j = getObjectId(getObjectId); | |
eq(a, getObjectId(0)); | |
eq(b, getObjectId(1)); | |
eq(c, getObjectId("a")); | |
eq(d, getObjectId("")); | |
eq(e, getObjectId("hasOwnProperty")); | |
eq(f, getObjectId(null)); | |
eq(g, getObjectId(undefined)); | |
eq(h, getObjectId(true)); | |
eq(i, getObjectId(false)); | |
eq(j, getObjectId(getObjectId)); | |
ne(a, b, c, d, e, f, g, h, i, j); | |
}) // (); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment