Skip to content

Instantly share code, notes, and snippets.

@davemo
Last active August 29, 2015 14:07
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 davemo/cb6ce0344371f1a122d7 to your computer and use it in GitHub Desktop.
Save davemo/cb6ce0344371f1a122d7 to your computer and use it in GitHub Desktop.
// Define a function greaterThan(n), that takes a value and returns a predicate
// which returns truthy if that value is greater than n.
var greaterThan = function(n) {
return function(value) {
return value > n;
};
};
var greaterThanFour = greaterThan(4);
greaterThanFour(5); // true
greaterThanFour(3); // false
// Define the filter method using reduce.
Array.prototype.filter = function(predicate) {
return this.reduce(function(acc, value) {
if(predicate(value)){
acc.push(value);
}
return acc;
}, []);
};
[1,2,3,4,5,6].filter(function(v) { return v % 2 !== 0; }); // [1,3,5];
// Define a function Array.reject(predicate),
// which is like filter, but only retains values that
// fail the predicate passed.
Array.prototype.reject = function(predicate) {
return this.reduce(function(acc, value) {
if(!predicate(value)) {
acc.push(value);
}
return acc;
}, []);
};
[1,2,3,4,5,6].reject(function(v) { return v % 2 === 0; }); // [1,3,5];
// Define a function throttle(fn, duration),
// a function that takes a function and a duration in
// milli-seconds as input. Which returns a function that mimics the
// function that was passed in, but ensures the function can not be run
// for the duration passed after it is called, when that duration completes
// the function should be free to be run again.
var throttle = function(fn, duration) {
var lastRan = 0;
return function() {
var now = Date.now();
var remaining = duration - (now - lastRan);
if(remaining <= 0) {
lastRan = now;
return fn.apply(fn, arguments);
} else { console.log('cant run for ', remaining, 'more ms'); }
};
};
var sayHi = function(msg) { console.log(msg); };
var throttledSayHi = throttle(sayHi, 750);
throttledSayHi('hi mom'); // hi mom
throttledSayHi('hi mom'); // can't run for [x] more ms
// 750ms passes
throttledSayHi('hi mom'); // hi mom
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment