Last active
December 7, 2018 22:53
-
-
Save mattdiamond/ea3fabd2df1ddee48f7b803d6332aeda to your computer and use it in GitHub Desktop.
Fun with Javascript Prototypes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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