Skip to content

Commit

Permalink
feat: added removeN() operation
Browse files Browse the repository at this point in the history
  • Loading branch information
andres-kovalev committed Nov 1, 2019
1 parent 9c47290 commit 0dce914
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/operations/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const update = require('./update');
const set = require('./set');
const remove = require('./remove');
const removeN = require('./removeN');
const push = require('./push');
const pushAll = require('./pushAll');
const pop = require('./pop');
Expand All @@ -14,6 +15,7 @@ module.exports = {
update,
set,
remove,
removeN,
push,
pushAll,
pop,
Expand Down
56 changes: 56 additions & 0 deletions src/operations/removeN/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const { updateArray, isNumber, extractSubPath } = require('../common');

module.exports = removeN;

/**
* Removes number of elements from array-item selected by path
* @param {Object | any[]} object object to update
* @param {string | string[]} path path to first item to be removed
* (array of items or dot-separated string can be provided)
* @param {number} n number of items to remove
* @returns {Object | any[]} updated object
* @description one of additional functions to work with array items
* @docs
* ```js
* import { removeN } from 'immutable-object-update';
*
* const state = {
* a: {
* b: [ 1, 2, 3, 4, 5, 6 ]
* },
* };
*
* const updated = removeN(state, [ 'a', 'b', 1 ], 3);
*
* // or
*
* const updated = removeN(state, 'b.b1.1', 3);
* ```
*
* As a result we will receive new object with structure below:
*
* ```js
* {
* a: {
* b: [ 1, 5, 6 ]
* }
* }
* ```
*
* > Please note: `removeN()` function won't return removed items
*/
function removeN(object, path, n) {
const [ itemPath, valuePath ] = extractSubPath(path);

if (!isNumber(valuePath)) {
return object;
}

return updateArray(
object,
itemPath,
array => array
.slice(0, valuePath)
.concat(array.slice(+valuePath + n))
);
}

0 comments on commit 0dce914

Please sign in to comment.