Skip to content

Instantly share code, notes, and snippets.

@zpao
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zpao/d25251b139647a79cddf to your computer and use it in GitHub Desktop.
Save zpao/d25251b139647a79cddf to your computer and use it in GitHub Desktop.
Why we have keyMirror - Google Closure Compiler examples
function d(c) {
var b = {}, a;
for (a in c) {
c.hasOwnProperty(a) && (b[a] = a);
}
return b;
}
var e = d({a:null, b:null, c:null}), f = d({a:null}), g = function(c) {
var b = {};
c.forEach(function(a) {
b[a] = a;
});
return b;
}(["foo", "bar", "qux"]);
alert(e.a);
alert(f.a);
alert(g.a);
alert(g.foo);
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @formatting pretty_print
// ==/ClosureCompiler==
// Ours
var keyMirror = function(obj) {
var ret = {};
var key;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
// With array of strings
var keyMirrorArr = function(arr) {
var ret = {};
arr.forEach(function(key) {
ret[key] = key;
});
return ret;
};
// Keys in resulting object will be crushed in advanced mode and object will look like {a: 'a', b: 'b', c: 'c'}
var mirror = keyMirror({
foo: null,
bar: null,
qux: null
});
// Just here so keyMirror doesn't get inlined
var mirror2 = keyMirror({foo: null})
// This object will look like {foo: 'foo', bar: 'bar', qux: 'qux'}, even after crushing.
var mirrorArr = keyMirrorArr(['foo', 'bar', 'qux']);
// Notice this key gets crushed, in fact anything written as .foo gets crushed to the same thing.
alert(mirror.foo);
// ignore this
alert(mirror2.foo);
// This is crushed but the keys in our object weren't. So now we actually have a bug.
alert(mirrorArr.foo);
// You would have to use it like this, which does not get crushed.
alert(mirrorArr['foo']);
var keyMirror = function(c) {
var b = {}, a;
for (a in c) {
c.hasOwnProperty(a) && (b[a] = a);
}
return b;
}, keyMirrorArr = function(c) {
var b = {};
c.forEach(function(a) {
b[a] = a;
});
return b;
}, mirror = keyMirror({foo:null, bar:null, qux:null}), mirror2 = keyMirror({foo:null}), mirrorArr = keyMirrorArr(["foo", "bar", "qux"]);
alert(mirror.foo);
alert(mirror2.foo);
alert(mirrorArr.foo);
alert(mirrorArr.foo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment