From 1f351876cfa9ff99f4a0da46ca1877dfd20269e7 Mon Sep 17 00:00:00 2001 From: mohammad matin fotouhi Date: Thu, 4 Feb 2021 10:50:47 +0330 Subject: [PATCH] added remove method + tests --- modules/index.js | 2 ++ modules/remove.js | 8 ++++++++ test/arrays.js | 15 +++++++++++++++ 3 files changed, 25 insertions(+) create mode 100644 modules/remove.js diff --git a/modules/index.js b/modules/index.js index c48ca7e9e..526854a73 100644 --- a/modules/index.js +++ b/modules/index.js @@ -191,6 +191,8 @@ export { default as zip } from './zip.js'; export { default as object } from './object.js'; export { default as range } from './range.js'; export { default as chunk } from './chunk.js'; +export { default as remove } from './remove.js'; + // OOP // --- diff --git a/modules/remove.js b/modules/remove.js new file mode 100644 index 000000000..4f1a42fc8 --- /dev/null +++ b/modules/remove.js @@ -0,0 +1,8 @@ +// removes first element having the condition +export default function remove(collection, predicate) { + var index = collection.length; + while(index--){ + if(predicate(collection[index])) collection.splice(index, 1) + } + return collection; +} \ No newline at end of file diff --git a/test/arrays.js b/test/arrays.js index 5330cb323..4b8286a0f 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -583,4 +583,19 @@ assert.deepEqual(_.chunk([10, 20, 30, 40, 50, 60, 70], 2), [[10, 20], [30, 40], [50, 60], [70]], 'chunk into parts of less then current array length elements'); assert.deepEqual(_.chunk([10, 20, 30, 40, 50, 60, 70], 3), [[10, 20, 30], [40, 50, 60], [70]], 'chunk into parts of less then current array length elements'); }); + + QUnit.test('remove', function(assert) { + var result = [1, 2, 3, 4] + _.remove(result, function(obj) {return(obj == 2)}) + assert.deepEqual(result, [1, 3, 4]); + result = [{a: 1}, {a:3, b: 2}, 3] + _.remove(result, function(obj) {return(obj.a == 3)}) + assert.deepEqual(result, [{a: 1}, 3]); + result = [{a: 1, b: 2}, {a: 1}, 3] + _.remove(result, function(obj) {return(obj.a == 1)}) + assert.deepEqual(result, [3]); + result = [{a: 1, b: 2, c: 3}, {a:1, c: 3}, {c: 3}] + _.remove(result, function(obj) {return(obj.a == 1 && obj.c == 3)}) + assert.deepEqual(result, [{c: 3}]); + }); }());