Skip to content

Commit

Permalink
feat: added pop() and popN() operations
Browse files Browse the repository at this point in the history
  • Loading branch information
andres-kovalev committed Oct 31, 2019
1 parent d7a527c commit b2b6a23
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/operations/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ const set = require('./set');
const remove = require('./remove');
const push = require('./push');
const pushAll = require('./pushAll');
const pop = require('./pop');
const popN = require('./popN');

module.exports = { update, set, remove, push, pushAll };
module.exports = { update, set, remove, push, pushAll, pop, popN };
42 changes: 42 additions & 0 deletions src/operations/pop/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const popN = require('../popN');

module.exports = pop;

/**
* Removes an element from the end of array-item selected by path
* @param {Object | any[]} object object to update
* @param {string | string[]} path path to be updated
* @returns {Object | any[]} updated object
* @description one of additional functions to work with array items
* @docs
* ```js
* import { pop } from 'immutable-object-update';
*
* const state = {
* a: {
* b: [ 1, 2, 3 ]
* }
* };
*
* const updated = pop(state, [ 'a', 'b' ]);
*
* // or
*
* const updated = pop(state, 'a.b');
* ```
*
* As a result we will receive new object with structure below:
*
* ```js
* {
* a: {
* b: [ 1, 2 ]
* }
* }
* ```
*
* > Please note: `pop()` function won't return removed item
*/
function pop(object, path) {
return popN(object, path, 1);
}
43 changes: 43 additions & 0 deletions src/operations/popN/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const { updateArray } = require('../common');

module.exports = popN;

/**
* Removes number of elements from the end of array-item selected by path
* @param {Object | any[]} object object to update
* @param {string | string[]} path path to be updated
* @param {number} n number of elements to remove
* @returns {Object | any[]} updated object
* @description one of additional functions to work with array items
* @docs
* ```js
* import { popN } from 'immutable-object-update';
*
* const state = {
* a: {
* b: [ 1, 2, 3 ]
* }
* };
*
* const updated = popN(state, [ 'a', 'b' ], 2);
*
* // or
*
* const updated = popN(state, 'a.b', 2);
* ```
*
* As a result we will receive new object with structure below:
*
* ```js
* {
* a: {
* b: [ 1 ]
* }
* }
* ```
*
* > Please note: `popN()` function won't return removed items
*/
function popN(object, path, n) {
return updateArray(object, path, array => array.slice(0, -n));
}

0 comments on commit b2b6a23

Please sign in to comment.