Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. const partialBinder = ((hole, rest) => {
  2. "use strict";
  3. function partiallyBound(fn, args, ...missing) {
  4. const argsLen = args.length;
  5. const missingIter = missing[Symbol.iterator]();
  6. for (let i = 0; i < argsLen; ++i) {
  7. switch (args[i]) {
  8. case hole: break;
  9. case rest: args.splice(i, 1, ...missing); return fn.apply(this, args);
  10. default: continue;
  11. }
  12. const { done, value } = missingIter.next();
  13. args[i] = done ? null : value;
  14. }
  15. return fn.apply(this, args);
  16. }
  17. function partialBinder(fn, ...args) {
  18. let symbolMask = 0;
  19. for (const a of args) {
  20. switch (a) {
  21. case hole:
  22. if (symbolMask & 1) break;
  23. symbolMask |= 0b10;
  24. continue;
  25. case rest:
  26. if (symbolMask & 1) break;
  27. symbolMask |= 0b01;
  28. default:
  29. continue;
  30. }
  31. throw new SyntaxError("illegal parameters");
  32. }
  33.  
  34. if (symbolMask) return partiallyBound.bind(this, fn, args);
  35. else return fn.bind(this, ...args);
  36. }
  37. return Object.defineProperties(partialBinder, {
  38. hole: { value: hole },
  39. rest: { value: rest },
  40. });
  41. })(Symbol("hole"), Symbol("rest"));
  42.  
  43. // partialBinder(console.log, 1, partialBinder.hole, 3)(2, 4)
  44. // 1, 2, 3
  45. // partialBinder(console.log, 1, partialBinder.hole, 3, partialBinder.rest)(2, 4)
  46. // 1, 2, 3, 4
  47.  
  48. // Partial Application Syntax
  49. // console.log(1, ?, 3)(2, 4)
  50. // 1, 2, 3
  51. // console.log(1, ?, 3, ...)(2, 4)
  52. // 1, 2, 3, 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement