Created
July 2, 2016 13:00
-
-
Save fleon/1644f2a4cbe2e124faefbf1c068fecb8 to your computer and use it in GitHub Desktop.
cyclic-copy.js
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 utils = { | |
forEach: function (obj, fn, ctx) { | |
if (obj === null || typeof obj === 'undefined') { | |
return | |
} | |
if (obj instanceof Array) { | |
for (var i = 0; i < obj.length; i++) { | |
if (fn.call(ctx, obj[i], i, obj)) { | |
break | |
} | |
} | |
return | |
} | |
var keys = Object.keys(obj), key | |
while ((key = keys.shift())) { | |
if (fn.call(ctx, obj[key], key, obj)) { | |
break | |
} | |
} | |
}, | |
copy: function copy(obj, map) { | |
if (typeof obj !== 'object') { return obj } | |
map = map || new WeakMap() | |
var copied, | |
Constructor = obj.constructor; | |
switch (Constructor) { | |
case RegExp: copied = new Constructor(obj); break; | |
case Date: copied = new Constructor(obj.getTime()); break; | |
default: copied = new Constructor(); | |
} | |
map.set(obj, copied) | |
utils.forEach(obj, function (value, key) { | |
copied[key] = map.get(value) || copy(value, map) | |
}) | |
return copied | |
} | |
} | |
module.exports = utils |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment