Last active
August 11, 2022 21:16
-
-
Save Mellen/f74894da78a153a33f6c7b5759465a0d to your computer and use it in GitHub Desktop.
A function that will turn a normal javascript function into one that allows for partial application
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() | |
{ | |
function unaryCall(arg) | |
{ | |
this.args = []; | |
return arg; | |
} | |
function partialise(initialFunction) | |
{ | |
let firstPart; | |
if(initialFunction.length < 2) | |
{ | |
firstPart = initialFunction; | |
} | |
else | |
{ | |
let handlers = []; | |
for(let i = 0; i < initialFunction.length; i++) | |
{ | |
const handler = | |
{ | |
next: null, | |
apply: function(target, thisArg, argumentsList) | |
{ | |
if(this.next) | |
{ | |
const uc = new unaryCall(argumentsList[0]); | |
uc.args = thisArg.args.concat(argumentsList); | |
return (new Proxy(unaryCall, this.next)).bind(uc); | |
} | |
else | |
{ | |
const args = thisArg.args.concat(argumentsList); | |
return initialFunction(...args); | |
} | |
} | |
}; | |
if(handlers.length > 0) | |
{ | |
const last = handlers[handlers.length-1]; | |
last.next = handler; | |
} | |
handlers.push(handler); | |
} | |
const firstUnary = new unaryCall(null); | |
firstPart = (new Proxy(unaryCall, handlers[0])).bind(firstUnary); | |
} | |
return firstPart; | |
} | |
const add = partialise((x,y,z) => x+y+z); | |
const add2 = add(2); | |
const add23 = add2(3); | |
const add211 = add2(11); | |
console.log(add23(4)); | |
console.log(add211(20)); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment