rolling-reduce
Reduce over collections without recomputing everything when new items arrive or when items in the source change.
example
sum
var reduce = ;var summer = ;summer;summer;summer;summer;7 8 9; // 7 + 8 + 9 = 24summer; // 24 - 7 = 17summer; // 17 - 9 + 10 = 18summer; // 18 + 11 = 29
$ node example/sum.js
sum=7
sum=15
sum=24
sum=17
sum=18
sum=29
pairs
var reduce = ;var pairs = ;{for var i = 0; i < xslength; i++if xsi0 === xid return i;return -1;}pairs;pairs;pairs;pairs;var abc = id : 'abc' value : 7 ;pairs;var def = id : 'def' value : 8 ;pairs;var ghi = id : 'ghi' value : 9 ;pairs;pairs;pairs;var xyz = id : 'xyz' value : 5 ;pairs;
$ node example/pairs.js
pairs=[["abc",7]]
pairs=[["abc",7],["def",8]]
pairs=[["abc",7],["def",8],["ghi",9]]
pairs=[["def",8],["ghi",9]]
pairs=[["def",555],["ghi",9]]
pairs=[["def",555],["ghi",9],["xyz",5]]
methods
var reduce =
var r = reduce(init)
Create a reduce object r
from an initial accumulator value init
.
The event handlers 'insert'
, 'update'
, and 'remove'
are responible for
computing the reduction on the accumulator.
r.insert(x)
Insert a new object x
into the source.
r.update(xPrev, x)
Update over the previous item xPrev
with a new source item x
.
r.remove(x)
Remove the item x
from the source.
events
r.on('insert', cb)
The callback cb(acc,x)
fires when r.insert(x)
is called.
cb(acc,x)
should return the new value for the accumulator acc
.
r.on('update', cb)
The callback cb(acc,xPrev,x)
fires when r.update(xPrev,x)
is called.
Note that xPrev
and x
are merely a convention and the values from
r.update()
are passed directly through.
cb(acc,xPrev,x)
should return the new value for the accumulator acc
.
r.on('remove', cb)
The callback cb(acc,x)
fires when r.remove(x)
is called.
Note that x
is merely a convention and you can choose to signify elements in
any scheme that you like.
cb(acc,x)
should return the new value for the accumulator acc
.
install
With npm do:
npm install rolling-reduce
license
MIT