Skip to content

Instantly share code, notes, and snippets.

@HERRKIN
Created June 4, 2014 03:05
Show Gist options
  • Save HERRKIN/6e434532206069e6697d to your computer and use it in GitHub Desktop.
Save HERRKIN/6e434532206069e6697d to your computer and use it in GitHub Desktop.
Here is the puzzle. It is expressed in coffeescript, but you can answer in javascript or coffeescript.
Imagine you have a function that accesses a resource asynchronously. However, the resource is not able to handle too many concurrent requests. In order to control the number of concurrent requests, you will need to design a function throttle.
- A function throttle takes an asynchronous function and a concurrency limit as its arguments and returns a throttled version:
throttledFunction = throttler(asyncFunction, concurrencyLevel)
- The asynchronous function will always have as its last argument a callback function, which is called with the result as its only argument.
- A resource is "in use" between the time the asynchronous function starts and the time it calls its callback with the result.
- If the throttler sees too many calls to the asynchronous function simultaneously, then it queues the extra calls and waits until a callback is c alled before starting a new execution.
Please write a "throttler" function that can be used in the following code:
Assume this is your asynchronous function:
asyncFunction = (x, callback) -> setTimeout (-> callback(x*x)), 1000
Here is how you invoke the throttler:
throttledFunction = throttler(asyncFunction, 3 /* run max 3 concurrently */ )
The new throttled function works like this:
throttledFunction(1,(y)->console.log(y))throttledFunction(2,(y)->console.log(y))throttledFunction(3,(y)->console.log(y))
Now we expect to wait until at least one of the above completes before we:
throttledFunction(4,(y)->console.log(y))throttledFunction(5,(y)->console.log(y))throttledFunction(6,(y)->console.log(y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment