Skip to content

Instantly share code, notes, and snippets.

@fleon
Created July 2, 2016 13:00
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 fleon/1644f2a4cbe2e124faefbf1c068fecb8 to your computer and use it in GitHub Desktop.
Save fleon/1644f2a4cbe2e124faefbf1c068fecb8 to your computer and use it in GitHub Desktop.
cyclic-copy.js
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