Skip to content

Instantly share code, notes, and snippets.

@mfix22
Created February 20, 2018 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfix22/f08d913cf4a0792ed00332e876f5efd4 to your computer and use it in GitHub Desktop.
Save mfix22/f08d913cf4a0792ed00332e876f5efd4 to your computer and use it in GitHub Desktop.
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