diff --git a/lib/functional.js b/lib/functional.js index 0d06f6e..03ee587 100644 --- a/lib/functional.js +++ b/lib/functional.js @@ -125,6 +125,30 @@ function nerf(fn, context = null){ } +/** + * Keep calling a function until it returns a truthy value. + * + * @example poll(async () => (await fetch(url)).done); + * @param {Function} fn + * @param {Object} [opts={}] + * @param {Number} [opts.rate=100] + * @param {Number} [opts.timeout=0] + * @param {Boolean} [opts.negate=false] + * @return {Promise} + */ +async function poll(fn, opts = {}){ + const {rate = 100, timeout = 0, negate = false} = opts; + const start = Date.now(); + for(;;){ + const result = await fn(); + if(!negate === !!result) return result; + if(timeout && Date.now() - start > timeout) + throw new Error("Timed out"); + await new Promise($ => setTimeout($, rate)); + } +} + + /** * Monkey-patch an object's method with another function. *