From 3323d15bacfa588fe65cbe276eff0b488c1d2023 Mon Sep 17 00:00:00 2001 From: YasmineNk Date: Thu, 7 Aug 2025 20:32:38 +0200 Subject: [PATCH] partition_object_method --- helpful.js | 20 ++++++++++++++++++++ test/tester.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/helpful.js b/helpful.js index d39db91..5c65c62 100644 --- a/helpful.js +++ b/helpful.js @@ -9,6 +9,26 @@ }(typeof self !== 'undefined' ? self : this, function() { const helpful = {}; + + // partitionObject #30 + + helpful.partitionObject = function(obj, predicate) { + return Object.entries(obj).reduce( + ([pass, fail], [key, value]) => { + if (predicate(key, value)) { + pass[key] = value; + } else { + fail[key] = value; + } + return [pass, fail]; + }, + [{}, {}] + ); + }; + + + + helpful.stringToArray = function(string) { if(string == null) { return ""; diff --git a/test/tester.js b/test/tester.js index 200e993..2aad5b9 100644 --- a/test/tester.js +++ b/test/tester.js @@ -3,8 +3,39 @@ const assert = require("assert"); describe("Tests", function() { describe("General", function() { + let i = 0; + + i++; + it(`${i}: partitionObject - Should partition object by value > 2`, function () { + let expected = [{ c: 3, d: 4 }, { a: 1, b: 2 }]; + let actual = helpful.partitionObject({ a: 1, b: 2, c: 3, d: 4 }, (k, v) => v > 2); + assert.deepEqual(actual, expected); + }); + + i++; + it(`${i}: partitionObject - Should partition object by key === 'a'`, function () { + let expected = [{ a: 1 }, { b: 2, c: 3, d: 4 }]; + let actual = helpful.partitionObject({ a: 1, b: 2, c: 3, d: 4 }, (k, v) => k === "a"); + assert.deepEqual(actual, expected); + }); + + i++; + it(`${i}: partitionObject - Should return all in first if predicate always true`, function () { + let expected = [{ a: 1, b: 2 }, {}]; + let actual = helpful.partitionObject({ a: 1, b: 2 }, () => true); + assert.deepEqual(actual, expected); + }); + + i++; + it(`${i}: partitionObject - Should return all in second if predicate always false`, function () { + let expected = [{}, { a: 1, b: 2 }]; + let actual = helpful.partitionObject({ a: 1, b: 2 }, () => false); + assert.deepEqual(actual, expected); + }); + + i++; it(`${i}: stringToArray - should convert string to array`, function() { let expected = ["t", "e", "s", "t"];