Created
February 20, 2018 19:21
-
-
Save mfix22/f08d913cf4a0792ed00332e876f5efd4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const noop = () => {} | |
function batch (reduce, options = {}) { | |
const timeout = options.timeout || 1000 | |
const max = options.max || 10 | |
let calls = [] | |
let cancel = noop | |
let flush = noop | |
const reset = () => { | |
clearTimeout(cancel) | |
calls = [] | |
cancel = noop | |
flush = noop | |
} | |
return Object.assign( | |
(...args) => { | |
calls.push(args) | |
flush = () => { | |
clearTimeout(cancel) | |
reduce(calls) | |
reset() | |
} | |
if (calls.length >= max) { | |
flush() | |
return; | |
} | |
clearTimeout(cancel) | |
cancel = setTimeout(flush, timeout) | |
}, | |
{ | |
cancel: reset, | |
flush: () => flush() | |
} | |
) | |
} | |
// return () => calls.filter(c => c !== args) | |
const reducer = calls => console.log(calls.reduce((t, [f]) => t + f, '')) | |
const fn = batch(reducer, { timeout: 1000, max: 5 }) | |
fn('M') | |
fn('i') | |
fn('k') | |
fn('e') | |
fn.flush() | |
fn('F') | |
fn('i') | |
fn('x') | |
fn.cancel() | |
//stdout: "Mike" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment