I'm trying to implement Lodash's _.throttle
. I understand what needs to be returned (the total variable) but can't figure out how to put everything together. There are mocha tests written that are helping me understand this which I'll post below.
I've read several blog posts on the topic and tried using setTimeout
in conjunction with a boolean that determines if the setTimeout
needs to be run, but my tests keep failing.
/*
Throttle
Creates and returns a new, throttled version of the passed function, that, when
invoked repeatedly, will only actually call the original function at most once
per every wait milliseconds. Useful for rate-limiting events that occur faster
than you can keep up with.
Example:
let total = 0;
const count = () => ++total;
const throttleCount = throttle(count, 200);
throttleCount()
=> 1
throttleCount()
=> 1
// Wait 200ms and then:
throttleCount()
=> 2
throttleCount()
=> 2
*/
// Your code here!
let total = 0;
const count = () => {
return ++total
}
function throttle(callback, delay) {
let wait = false
return function() {
if (!wait) {
wait = true
callback()
return total
} else {
setTimeout(function() {
wait = false
}, delay)
return total
}
}
}
const throttleCount = throttle(count, 200)
throttleCount()
throttleCount()
throttleCount()
throttleCount()
throttleCount()
throttleCount()
const assert = require('assert');
describe('Throttle', () => {
it('returns a function', () => {
const exampleThrottle = throttle(() => {})
assert.equal(typeof exampleThrottle, 'function');
});
it('effectively throttles', (done) => {
let total = 0;
const count = () => ++total;
const throttleCount = throttle(count, 200);
assert.equal(throttleCount(), 1);
assert.equal(throttleCount(), 1);
// Wait 200ms and try again
new Promise(resolve => setTimeout(resolve, 200)).then(() => {
assert.equal(throttleCount(), 2);
assert.equal(throttleCount(), 2);
done()
})
});
});
I can't return the setTimeout
as that comes through as undefined. I also keep just returning 1 using my current code.