diff --git a/src/index.js b/src/index.js index 419ddee..493dc4e 100644 --- a/src/index.js +++ b/src/index.js @@ -19,9 +19,25 @@ export default function klona(x) { return tmp; } - if (str === '[object Set]') return new Set(x); - if (str === '[object Date]') return new Date(+x); - if (str === '[object Map]') return new Map(x); + if (str === '[object Set]') { + tmp = new Set(); + x.forEach(function (val) { + tmp.add(klona(val)); + }); + return tmp; + } + + if (str === '[object Map]') { + tmp = new Map(); + x.forEach(function (val, key) { + tmp.set(key, klona(val)); + }); + return tmp; + } + + if (str === '[object Date]') { + return new Date(+x); + } if (str === '[object RegExp]') { tmp = new RegExp(x.source, x.flags); diff --git a/test/index.js b/test/index.js index 86d1a2e..634516e 100644 --- a/test/index.js +++ b/test/index.js @@ -138,7 +138,7 @@ test('function', t => { }); -test('map', t => { +test('map :: flat', t => { const input = new Map(); const output = klona(input); @@ -154,6 +154,28 @@ test('map', t => { }); +test('map :: nested', t => { + const input = new Map([ + ['foo', { a: 1 }], + ['bar', [1, 2, 3]], + ]); + const output = klona(input); + + const foo = output.get('foo'); + foo.b = 2; + foo.a++; + + t.deepEqual(input.get('foo'), { a: 1 }); + t.deepEqual(output.get('foo'), { a: 2, b: 2 }); + + output.get('bar').push(4, 5, 6); + t.deepEqual(input.get('bar'), [1, 2, 3]); + t.deepEqual(output.get('bar'), [1, 2, 3, 4, 5, 6]); + + t.end(); +}); + + test('null', t => { let input = null; let output = klona(input); @@ -264,7 +286,7 @@ test('regexp :: state', t => { }); -test('set', t => { +test('set :: flat', t => { const input = new Set('hello'); const output = klona(input); @@ -279,6 +301,22 @@ test('set', t => { t.end(); }); +test('set :: nested', t => { + const input = new Set([{ foo: 123 }]); + const output = klona(input); + + t.deepEqual(input, output); + + const [obj] = [...output.keys()]; + obj.bar = 456; + obj.foo++; + + const [item] = [...input.keys()]; + t.deepEqual(item, { foo: 123 }); + + t.end(); +}); + test('string', t => { let input = 'hello';