Skip to content

Instantly share code, notes, and snippets.

@mattdiamond
Last active December 7, 2018 22:53
Show Gist options
  • Save mattdiamond/ea3fabd2df1ddee48f7b803d6332aeda to your computer and use it in GitHub Desktop.
Save mattdiamond/ea3fabd2df1ddee48f7b803d6332aeda to your computer and use it in GitHub Desktop.
Fun with Javascript Prototypes
Function.prototype.if = function (conditional) {
return input => conditional(input) ? this(input) : input;
}
let double = x => x * 2;
let positive = x => x > 0;
[2, -4, 6, -8].map(double.if(positive));
// [4, -4, 12, -8]
Function.prototype.patch = function (func) {
return (...args) => func.apply(this, args);
}
double = double.patch(function (input) {
console.log(`about to double ${input}`);
const result = this(input);
console.log('we did it');
return result;
});
[2, -4, 6, -8].map(double.if(positive));
// about to double 2
// we did it
// about to double 6
// we did it
// [4, -4, 12, -8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment