Skip to content

Commit

Permalink
feat: 🎸 add updateSpread operator
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitriz committed Dec 26, 2022
1 parent a9d7938 commit ffef10a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,16 @@ exports.curryGroupsN = n => f => {
*/
exports.update = reducer => state => (...vals) => {state = reducer(state, ...vals); return state}

/**
* Same as `update` but spread return values of curried reducer.
* This allows to update tuples rather than single values as `update` does.
* Reducer is curried for clean separation of arguments.
* As JavaScript has no tuples, use arrays instead.
*
* @param {Function} reducer: (s0,...,sn) -> (x0,...,xm) -> (s0,...,sn)
* @returns {Function} updateSpread(reducer): (s0,...,sn) -> (x0,...,xn) -> reducer(s0,...,sn)(x0,...,xm)
*/
exports.updateSpread = reducer => (...state) => (...vals) => {state = reducer(...state)(...vals); return state}

/**
* Pass tuple of values to sequence of functions similar to UNIX pipe
Expand Down
4 changes: 2 additions & 2 deletions test/update.test.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
const test = require('./config')
const { update } = require('..')

test('update transforms simple reducer to updateulator', t=>{
test('update transforms simple reducer to updater', t=>{
const add = update((state,v)=>state+v)(10)
t.is(add(1),10+1)
t.is(add(2),10+1+2)
t.is(add(-1),10+1+2-1)
})

test('update works with reducer with variadic tuples of values', t=>{
const concat = update((arr, ...rest)=>arr.concat(rest))([0])
const concat = update((arr, ...rest) => [...arr, ...rest])([0])
t.deepEqual(concat(1),[0,1])
t.deepEqual(concat(),[0,1])
t.deepEqual(concat(1,2,3),[0,1,1,2,3])
Expand Down
16 changes: 16 additions & 0 deletions test/updateSpread.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const test = require('./config')
const { updateSpread } = require('..')

test('updateSpread transforms simple curried reducer that returns array', t=>{
const add = updateSpread(state => v =>[state+v])(10)
t.deepEqual(add(1),[10+1])
t.deepEqual(add(2),[10+1+2])
t.deepEqual(add(-1),[10+1+2-1])
})

test('updateSpread works with curried reducer with variadic tuples of values', t=>{
const concat = updateSpread((...arr) => (...vals) => [...arr, ...vals])(0,0)
t.deepEqual(concat(1),[0,0,1])
t.deepEqual(concat(),[0,0,1])
t.deepEqual(concat(1,2,3),[0,0,1,1,2,3])
})

0 comments on commit ffef10a

Please sign in to comment.