Skip to content

Commit

Permalink
fix: handle nested Set/Map correctly;
Browse files Browse the repository at this point in the history
- also enables IE11 support;
- Closes #9
  • Loading branch information
lukeed committed Jan 10, 2020
1 parent 9b32695 commit dd79cb1
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 5 deletions.
22 changes: 19 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
42 changes: 40 additions & 2 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ test('function', t => {
});


test('map', t => {
test('map :: flat', t => {
const input = new Map();
const output = klona(input);

Expand All @@ -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);
Expand Down Expand Up @@ -264,7 +286,7 @@ test('regexp :: state', t => {
});


test('set', t => {
test('set :: flat', t => {
const input = new Set('hello');
const output = klona(input);

Expand All @@ -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';
Expand Down

0 comments on commit dd79cb1

Please sign in to comment.