diff --git a/README.md b/README.md index 2e17d3f..d511a51 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,22 @@ console.log(arr.remove(2)) // => [1,3,4,5] ``` +### *Array.yank()* +Returns and removes the specified values and mutates the actual array +``` javascript +const arr = [1,2,3,4,5] + +console.log(arr.yank(2)) +// => 2 +console.log(arr) +// => [1,3,4,5] + +console.log(arr.yank([3,4])) +// => [3,4] +console.log(arr) +// => [1,2,5] +``` + ### *Array.clear()* Clear the array being worked on, and return a new empty array ``` javascript diff --git a/src/Array/extensions.js b/src/Array/extensions.js index 06ebd5c..dfee3a6 100644 --- a/src/Array/extensions.js +++ b/src/Array/extensions.js @@ -50,6 +50,33 @@ extensionArray.remove = function remove(selector) { return this; }; +/** + * Remove all instances of a value within the array and return the removed value + * @param {*} value - The value trying to match against + * @returns {*} - Value removed from the array + */ +extensionArray.yank = function yank(value){ + if (value.constructor === Array) { + for (let i = 0; i < value.length; i++) { + if(this.includes(value[i])){ + this.remove(value[i]); + }else{ + // Remove it from the given array so when we return it, it doesnt + // return a number that was not removed + value.remove(value[i]); + i -= 1; //array shrinks after removing so need to check previous element + } + } + if(value.isEmpty()) return null; + return value; + } else if (this.includes(value)) { + this.remove(value); + return value; + } else{ + return null; + } +} + /** * Get the value of the array by the position of the index * @param {number} index - The value being accessed, supports negative indexing diff --git a/test/Array.test.js b/test/Array.test.js index 3653124..bff38cb 100644 --- a/test/Array.test.js +++ b/test/Array.test.js @@ -68,6 +68,32 @@ describe('array prototype', () => { }) }) + describe('Array yank prototype', () => { + it('should return removed values and mutate the array ', () => { + const array = [1, 2, 2, 2, 2, 3, 4] + assert.deepEqual(array.yank(2), 2) + assert.deepEqual(array, [1, 3, 4]) + + const array2 = [1, 2, 2, 2, 2, 3, 4] + assert.deepEqual(array2.yank([3,4]), [3,4]) + assert.deepEqual(array2, [1, 2, 2, 2, 2]) + + const array3 = [1, 2, 2, 2, 2, 3, 4] + assert.deepEqual(array3.yank([4,5]), [4]) + assert.deepEqual(array3, [1, 2, 2, 2, 2, 3]) + + const array4 = [1, 2, 2, 2, 2, 3, 4] + assert.deepEqual(array4.yank(5), null) + assert.deepEqual(array4, [1, 2, 2, 2, 2, 3, 4]) + + assert.deepEqual(array4.yank([5,6,7]), null) + assert.deepEqual(array4, [1, 2, 2, 2, 2, 3, 4]) + + assert.deepEqual(array4.yank([5]), null) + assert.deepEqual(array4, [1, 2, 2, 2, 2, 3, 4]) + }) + }) + describe('Array findObj prototype', () => { it('should find the obj in the array with the findObj function', () => { const res = users.findObj(o => { return o.age < 40 })