Skip to content

Instantly share code, notes, and snippets.

@Jberivera
Last active February 15, 2017 18:18
Show Gist options
  • Select an option

  • Save Jberivera/f997a04310466bad881083e45584cb52 to your computer and use it in GitHub Desktop.

Select an option

Save Jberivera/f997a04310466bad881083e45584cb52 to your computer and use it in GitHub Desktop.
/**
* createTakeLastOneContext - Returns a function that uses its context
* to know the last time it was called
* @returns {Function} takeLastOne function.
*/
function createTakeLastOneContext () {
var _lastOne = 0,
_timeStamp = 0;
return function takeLastOne (callback) {
var count = ++_lastOne,
timeStamp = _timeStamp = (new Date()).getTime();
/**
* takeLastOne - Handles a callback function based on its knowledge
* of times it was invoked before and only runs the last callback it was passed.
* @returns {Function} callback function decorated with takeLastOne
*/
return function () {
var context = this,
args = arguments;
if (count === _lastOne && timeStamp === _timeStamp) {
_lastOne = _timeStamp = 0;
callback.apply(context, args);
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment