From 9a3e74cefad84a71a776bf960a109bfaf06be12f Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 5 Jan 2020 21:40:39 +0200 Subject: [PATCH] Add haveSameContents snippet --- snippets/haveSameContents.md | 23 +++++++++++++++++++++++ test/haveSameContents.test.js | 17 +++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 snippets/haveSameContents.md create mode 100644 test/haveSameContents.test.js diff --git a/snippets/haveSameContents.md b/snippets/haveSameContents.md new file mode 100644 index 000000000..4168dd7aa --- /dev/null +++ b/snippets/haveSameContents.md @@ -0,0 +1,23 @@ +--- +title: haveSameContents +tags: array,intermediate +--- + +Returns `true` if two arrays contain the same elements regardless of order, `false` otherwise. + +Use a `for...of` loop over a `Set` created from the values of both arrays. +Use `Array.prototype.filter()` to compare the amount of occurences of each distinct value in both arrays. +Return `false` if the counts do not match for any element, `true` otherwise. + +```js +const haveSameContents = (a, b) => { + for (const v of new Set([...a, ...b])) + if (a.filter(e => e === v).length !== b.filter(e => e === v).length) + return false; + return true; +} +``` + +```js +haveSameContents([1, 2, 4], [2, 4, 1]); // true +``` diff --git a/test/haveSameContents.test.js b/test/haveSameContents.test.js new file mode 100644 index 000000000..fd6632a45 --- /dev/null +++ b/test/haveSameContents.test.js @@ -0,0 +1,17 @@ +const {haveSameContents} = require('./_30s.js'); + +test('haveSameContents is a Function', () => { + expect(haveSameContents).toBeInstanceOf(Function); +}); +test('returns true for arrays with same contents', () => { + expect(haveSameContents([1, 2, 3], [2, 3, 1])).toBeTruthy(); +}); +test('returns false for arrays with different contents', () => { + expect(haveSameContents([1, 2], [2, 3, 1])).toBeFalsy(); +}); +test('returns false for arrays with different contents', () => { + expect(haveSameContents([1, 2, 3], [2, 1])).toBeFalsy(); +}); +test('returns false for arrays with different contents', () => { + expect(haveSameContents([1, 2, 3], [2, 1, 6])).toBeFalsy(); +});