Skip to content

Instantly share code, notes, and snippets.

@wentout
Last active August 16, 2020 21:40
Show Gist options
  • Select an option

  • Save wentout/02bd3fd6188c014e4947e36321a816d8 to your computer and use it in GitHub Desktop.

Select an option

Save wentout/02bd3fd6188c014e4947e36321a816d8 to your computer and use it in GitHub Desktop.
Arity From Callback
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
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
@wentout
Copy link
Author

wentout commented Aug 16, 2020

much better here )

omg-curry/fixed.js at master · Debdut/omg-curry
https://github.com/Debdut/omg-curry/blob/master/src/fixed.js

function fixed (f) {
  return function next (...a) {
    if (a.length < f.length) {
      return function (...b) {
        return next(...a, ...b)
      }
    }
    return f(...a)
  }
}

export default fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment