JSFiddle - React, Tailwind, and code Playground
HTML
<button
id='example1'
onClick='$("#result1").val(myCalc.multiply(2, 3))'
>myCalc.multiply(2, 3)</button>
<input type='text' id='result1'/>
<br/>
<button
id='example2'
onClick='$("#result2").val(myCalc.back())'
>myCalc.back()</button>
<input type='text' id='result2'/>
<br/>
<br/>
<h3>Crockford's example, context set to null (and therefore the global object)</h3>
<button
id='example3'
onClick='Crockford();'
>myCalc.multiplyPi = myCalc.multiply.curry(Math.PI);</button>
<br/>
myCalc.multiplyPi(1);
<br/>
<textarea id='result3a'></textarea>
<br/>
myCalc.back();
<br/>
<textarea id='result3b'></textarea>
<br/>
<br/>
<h3>Alternate example, context set to the value of `this` at the time `myCurry` is called</h3>
<button
id='example4'
onClick='Alternate();'
>myCalc.multiplyPi = myCalc.multiply.myCurry(Math.PI);</button>
<br/>
myCalc.multiplyPi(1);
<br/>
<textarea id='result4a'></textarea>
<br/>
myCalc.back();
<br/>
<textarea id='result4b'></textarea>
JavaScript
Function.prototype.curry = function(){
var slice = Array.prototype.slice,
args = slice.apply(arguments),
that = this;
return function() {
// context set to null
return that.apply(null, args.concat(slice.apply(arguments)));
};
};
Function.prototype.myCurry = function(){
var slice = [].slice,
args = slice.apply(arguments),
that = this;
return function() {
// context set to whatever `this` is when myCurry is called
return that.apply(this, args.concat(slice.apply(arguments)));
};
};
var calculator = {
history: [],
multiply: function(num1, num2){
this.history = this.history.concat([num1 + " * " + num2]);
return num1 * num2;
},
back: function(){
return this.history.pop();
}
};
myCalc = Object.create(calculator);
Crockford = function(){
myCalc.multiplyPi = myCalc.multiply.curry(Math.PI);
try {
$('#result3a').val(myCalc.multiplyPi(1));
} catch(e) {
$('#result3a').val(e + ": " + e.message);
}
$('#result3b').val(myCalc.back());
}
Alternate = function(){
myCalc.multiplyPi = myCalc.multiply.myCurry(Math.PI);
try {
$('#result4a').val(myCalc.multiplyPi(1));
} catch(e) {
$('#result4a').val(e + ": " + e.message);
}
$('#result4b').val(myCalc.back());
}