Skip to content

Commit

Permalink
fix: even no deep equal duplicates while merging array entries
Browse files Browse the repository at this point in the history
  • Loading branch information
arlac77 committed May 14, 2019
1 parent 721c233 commit 155e2ff
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
25 changes: 24 additions & 1 deletion src/util.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export function merge(a, b) {

if (Array.isArray(a)) {
if (Array.isArray(b)) {
return [...a, ...a.filter(x => !b.includes(x))];
return [...a, ...a.filter(x => !b.find(e => equal(e, x)))];
}
return [...a, b];
}
Expand All @@ -44,3 +44,26 @@ export function merge(a, b) {

return a;
}

export function equal(x, y) {
const xType = typeof x;
const yType = typeof y;

if (xType === "object" && yType === "object" && (x !== null && y !== null)) {
const xKeys = Object.keys(x);
const yKeys = Object.keys(y);
const xValues = Object.values(x);
const yValues = Object.values(y);

if (xKeys.length !== yKeys.length) return false;

for (let i = 0; i < xKeys.length; i++)
if (xKeys[i] !== yKeys[i]) return false;

for (let i = 0; i < xValues.length; i++)
if (!equal(xValues[i], yValues[i])) return false;
} else {
if (x !== y) return false;
}
return true;
}
19 changes: 18 additions & 1 deletion tests/merge-test.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import test from "ava";
import { expand } from "../src/expander.mjs";
import { equal } from "../src/util.mjs";

test("merge", async t =>
t.deepEqual(
await expand(
{ a: { b: "${1 - 1}", b1: 2, b3: 3}, a1: ["a"], a2: { b1: 7 } },
{ a: { b: "${1 - 1}", b1: 2, b3: 3 }, a1: ["a"], a2: { b1: 7 } },
{ default: { a: { b1: 1, b2: "${1 + 2}", b3: null } } }
),
{
Expand All @@ -14,6 +15,14 @@ test("merge", async t =>
}
));

test("merge complex array", async t =>
t.deepEqual(
await expand([{ a: 1 }, { b: 2 }], {
default: [{ a: 1 }, { b: 2 }]
}),
[{ a: 1 }, { b: 2 }]
));

test("merge array", async t =>
t.deepEqual(
await expand(
Expand All @@ -40,3 +49,11 @@ test("merge array", async t =>
}
}
));


test("eq1",t =>{
t.true(equal(1,1));
t.true(equal([1],[1]));
t.true(equal([{a:1}],[{a:1}]));
t.false(equal([{a:1}],[{b:1}]));
});

0 comments on commit 155e2ff

Please sign in to comment.