@everymundo/simple-clone
Advanced tools
Comparing version 1.0.0 to 1.1.0
23
index.js
const clone = o => JSON.parse(JSON.stringify(o)); | ||
module.exports = { clone }; | ||
const realClone = (obj, history = []) => { | ||
if (history.includes(obj)) return '[Circular]'; | ||
if (Array.isArray(obj)) { | ||
history.push(obj); | ||
return obj.map(_ => realClone(_, history)); | ||
} | ||
if (typeof obj === 'object') { | ||
history.push(obj); | ||
const ret = {}; | ||
Object.keys(obj).forEach((key) => { | ||
ret[key] = realClone(obj[key], history); | ||
}); | ||
return ret; | ||
} | ||
return obj; | ||
}; | ||
module.exports = { clone, realClone }; |
{ | ||
"name": "@everymundo/simple-clone", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "Very simplistic cloning tool for nodejs.", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
const { expect } = require('chai'); | ||
const { clone } = require('../'); | ||
const { clone, realClone } = require('../'); | ||
@@ -13,2 +13,36 @@ describe('clone', () => { | ||
}); | ||
}); | ||
describe('realClone', () => { | ||
it('should return a different obj with the same structure', () => { | ||
const original = {a: 1, b: 'two', c:[true], d:{e:'f'}}; | ||
const result = realClone(original); | ||
expect(result).to.not.equal(original); | ||
expect(result).to.deep.equal(original); | ||
}); | ||
it('should return a different Array with the copy of the values', () => { | ||
const original = [{a: 1}, {b: 'two'}, [true], {d:{e:'f'}}]; | ||
const result = realClone(original); | ||
expect(result).to.not.equal(original); | ||
expect(result).to.deep.equal(original); | ||
}); | ||
it('should return a clone of the input signalizing the Circular ref', () => { | ||
const someObject = { a: 1, original: '[Circular]' }; | ||
const original = [someObject, {b: 'two'}, [true], {d:{e:'f'}}]; | ||
// cloning original before adding Circular ref | ||
const expected = clone(original); | ||
// adds circular ref | ||
someObject.original = original; | ||
const result = realClone(original); | ||
expect(result).to.not.equal(original); | ||
expect(result).to.deep.equal(expected); | ||
}); | ||
}); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
3710
52