Skip to content

Instantly share code, notes, and snippets.

@gilbert
Last active September 20, 2016 15:09
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gilbert/13d4593b00b4ee7cea33 to your computer and use it in GitHub Desktop.
Save gilbert/13d4593b00b4ee7cea33 to your computer and use it in GitHub Desktop.
JavaScript Function Extensions
// Partially apply arguments to a function. Useful for binding
// specific data to an event handler.
// Example:
//
// var add = function (x,y) { return x + y }
// var add5 = add.papp(5)
// add5(7) //=> 12
//
Function.prototype.papp = function () {
var slice = Array.prototype.slice
var fn = this
var args = slice.call(arguments)
return function () {
return fn.apply(this, args.concat(slice.call(arguments)))
}
}
// Prevents the default action. Useful for preventing
// anchor click page jumps and form submits.
// Example:
//
// var x = 0
// var increment = function () { x += 1 }
// myAnchorEl.addEventListener('click', increment.chill())
//
Function.prototype.chill = function() {
var fn = this
return function(e) {
e.preventDefault()
return fn()
}
}
// Both prevent default and partially apply in one go.
// Example:
//
// var x = 0
// var increment = function (amount) { x += amount }
// myAnchorEl.addEventListener('click', increment.coldPapp(17))
//
Function.prototype.coldPapp = function() {
var slice = Array.prototype.slice
var fn = this
var args = slice.call(arguments)
return function(e) {
e.preventDefault()
return fn.apply(this, args.concat(slice.call(arguments, 1)))
}
}
Function.prototype.throttle = function (fn, waittime, threshhold, scope) {
threshhold || (threshhold = 250);
var last, deferTimer
var go = function () {
var context = scope || this
var now = +new Date,
args = arguments
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer)
deferTimer = setTimeout(function () {
last = now
fn.apply(context, args)
}, threshhold)
} else {
last = now
fn.apply(context, args)
}
}
var goTimeout = null
return function () {
clearTimeout(goTimeout)
goTimeout = setTimeout(go, waittime)
}
}
@Bondifrench
Copy link

Very useful functions, but check your maths: 5 +7 = 12!! in the description of papp add5(7) //=> 11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment