Skip to content

Commit

Permalink
feat: added reduce() operation
Browse files Browse the repository at this point in the history
  • Loading branch information
andres-kovalev committed Nov 1, 2019
1 parent bb30de5 commit d4fe4bb
Show file tree
Hide file tree
Showing 2 changed files with 54 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 @@ -14,6 +14,7 @@ const insert = require('./insert');
const insertAll = require('./insertAll');
const filter = require('./filter');
const map = require('./map');
const reduce = require('./reduce');

module.exports = {
update,
Expand All @@ -31,5 +32,6 @@ module.exports = {
insert,
insertAll,
filter,
map
map,
reduce
};
51 changes: 51 additions & 0 deletions src/operations/reduce/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const { updateArray } = require('../common');

module.exports = reduce;

/**
* Reduces array-item selected by path using provided reducer
* @param {Object | any[]} object object to update
* @param {string | string[]} path path to be updated
* @param {function} reducer reducer function
* @returns {Object | any[]} updated object
* @description one of additional functions to work with array items
* @docs
* ```js
* import { reduce } from 'immutable-object-update';
*
* const state = {
* a: {
* b: [ 1, 2, 3, 4, 5 ]
* }
* };
* const sum = (acc, item) => acc + item;
*
* const updated = reduce(state, [ 'a', 'b' ], sum);
*
* // or
*
* const updated = reduce(state, 'a.b', sum);
* ```
*
* As a result we will receive new object with structure below:
*
* ```js
* {
* a: {
* b: 15
* }
* }
* ```
*
* > Please note: first element of array will be always used as initial value
*/
function reduce(object, path, reducer) {
return updateArray(
object,
path,
array => array.reduce(
reducer,
...(array.length ? [] : [ undefined ])
)
);
}

0 comments on commit d4fe4bb

Please sign in to comment.