Skip to content

Instantly share code, notes, and snippets.

@detj
Last active December 18, 2016 20:58
Show Gist options
  • Select an option

  • Save detj/c9a9236a9a276248fcb9 to your computer and use it in GitHub Desktop.

Select an option

Save detj/c9a9236a9a276248fcb9 to your computer and use it in GitHub Desktop.
Creates an object by taking an array of keys, type of the key's value and key's default value. Contains an in-house deeply recursive object cloner
var keys = ['apple', 'orange', 'grape', 'banana'];
function gen(keys, type, def) {
var constructor = type.constructor;
var obj = {};
keys.forEach(function(key) {
obj[key] = typeof constructor === 'function' ? constructor(clone(def)) : undefined;
});
return obj;
function clone(obj) {
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor(); // changed
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
temp[key] = clone(obj[key]);
}
}
return temp;
}
}
// Tests
console.log(gen(keys, [], [1,2,3]));
console.log(gen(keys, 5, 100));
console.log(gen(keys, function() {}, 'args'));
console.log(gen(keys, new RegExp(), /m[a|e]n/g));
console.log(gen(keys, new Date()));
console.log(gen(keys, '', 'foo'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment