Last active
August 16, 2020 21:40
-
-
Save wentout/02bd3fd6188c014e4947e36321a816d8 to your computer and use it in GitHub Desktop.
Arity From Callback
This file contains hidden or 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
| const ArityWithCallback = function (callback) { | |
| // callback length is number of arguments | |
| // that callback can accept before | |
| // it has to be called | |
| const arity = callback.length; | |
| const storage = Array.isArray(this) ? this : []; | |
| if (arity === 0) { | |
| return callback; | |
| } | |
| const acceptArity = (...args) => { | |
| storage.push(...args); | |
| if (storage.length < arity) { | |
| return ArityWithCallback.call(storage, callback); | |
| } | |
| // calculation | |
| const result = callback(...storage.slice(0, arity)); | |
| // storage cleanup | |
| storage.length = 0; | |
| return result; | |
| }; | |
| return acceptArity; | |
| }; | |
| const func = (a, b, c, d, e) => a + b + c + d + e; | |
| const hof = ArityWithCallback(func); | |
| console.log(hof(1, 2, 3, 4, 5)); // 15 | |
| console.log(hof(2, 3, 4)(5, 6)); // 20 | |
| console.log(hof(3, 4)(5, 6)(7)); // 25 | |
| console.log(hof(4, 5)(6)(7, 8)); // 30 | |
| console.log(hof(5)(6)(7)(8)(9)); // 35 |
This file contains hidden or 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
| const ArityWithCallbackArrow = (callback, storage = []) => { | |
| // callback length is number of arguments | |
| // that callback can accept before | |
| // it has to be called | |
| const arity = callback.length; | |
| if (arity === 0) { | |
| return callback; | |
| } | |
| const acceptArity = (...args) => { | |
| storage.push(...args); | |
| if (storage.length < arity) { | |
| return ArityWithCallbackArrow(callback, storage); | |
| } | |
| // calculation | |
| const result = callback(...storage.slice(0, arity)); | |
| // storage cleanup | |
| storage.length = 0; | |
| return result; | |
| }; | |
| return acceptArity; | |
| }; | |
| const hof2 = ArityWithCallback(func); | |
| console.log(hof2(1, 2, 3, 4, 5)); // 15 | |
| console.log(hof2(2, 3, 4)(5, 6)); // 20 | |
| console.log(hof2(3, 4)(5, 6)(7)); // 25 | |
| console.log(hof2(4, 5)(6)(7, 8)); // 30 | |
| console.log(hof2(5)(6)(7)(8)(9)); // 35 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
much better here )
omg-curry/fixed.js at master · Debdut/omg-curry
https://github.com/Debdut/omg-curry/blob/master/src/fixed.js