diff --git a/src/util.mjs b/src/util.mjs index 7db35511..a7b7d4f3 100644 --- a/src/util.mjs +++ b/src/util.mjs @@ -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]; } @@ -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; +} diff --git a/tests/merge-test.mjs b/tests/merge-test.mjs index 66e7f66b..45377206 100644 --- a/tests/merge-test.mjs +++ b/tests/merge-test.mjs @@ -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 } } } ), { @@ -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( @@ -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}])); +});