Skip to content

Instantly share code, notes, and snippets.

@NateFerrero
Forked from jed/README.md
Created September 7, 2011 11:47
Show Gist options
  • Save NateFerrero/1200364 to your computer and use it in GitHub Desktop.
Save NateFerrero/1200364 to your computer and use it in GitHub Desktop.
Completely avoiding namespace collisions for 2-byte abbreviated keys for the document object

This version uses all possible ASCII variable names, i.e. È and the like! Don't know why I still have 4-5 collisions depending on environment.

/**
* Automatically makes a 2-byte hash namespace of global objects.
* Since .xxx is the same length as [xx], don't process unless > 3 chars
*/
var d = document;
var namespace = {};var coll = 0;
(function(v, m, n) {
m = {0:36, 37:28, 91:6, 123:69, 215:2, 247:2};
function c(x, q) {
for(q in m)
if(x >= q) x += m[q];
if(x > 255) return c(x - 256);
return String.fromCharCode(x);
}
for(n in d)
if(n.length > 3) {
v = n.split('').reduce(function(j, k, i) { return j + i * k.charCodeAt(0) }, 0);
console.log(v);
v = c(v % 256) + c(Math.floor(v / 256) % 256);
window[v] = n;
// debug
namespace[v] = namespace[v] || [];
if(namespace[v].length) coll++;
namespace[v].push(n);
// end
}
})();
alert(coll + ' collisions');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment