Advertisement
Guest User

curry

a guest
Jul 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. //-----------------------------curry-------------------------
  2. const add4=(a1,a2,a3,a4) => a1+a2+a3+a4;
  3. const curry= func => {
  4. const prevParams=[];
  5. const currFunc= (...params) => {
  6. prevParams.push(...params);
  7. if ( prevParams.length >= func.length ) {
  8. return func(...prevParams);
  9. }
  10. else{
  11. return currFunc;
  12. }
  13.  
  14. }
  15. return currFunc;
  16. }
  17.  
  18. const cAdd4=curry(add4);
  19. console.log(cAdd4(3,5)(4)(3),cAdd4(1,2,3,4));
  20. //------------------------curry better-----------------------------------
  21. // definitions
  22. const curry = func => function currFunc(...params) {
  23. if (params.length >= func.length) {
  24. return func(...params);
  25. }
  26. return (...moreParams) => currFunc(...params, ...moreParams);
  27. }
  28.  
  29. const partial = (func, ...params) => (...restParams) => func(...params, ...restParams); //partial
  30.  
  31. // examples
  32. const add4 = (a1, a2, a3, a4) => a1 + a2 + a3 + a4;
  33.  
  34. const cAdd4 = curry(add4);
  35. const x = cAdd4(4); //x exei params 4 execution context to ena mesa sto allo mexri to telos an grapsw y= x(3) neo mesa sto idio meros //me x1
  36. const x1 = x(5); //x1 exei params 5
  37. const x2 = x1(7); //x2 exei params 5
  38.  
  39. console.log(x2(5)); //to moreParams ginetai 5
  40.  
  41. const pAdd4 = partial(add4, 1, 3);
  42.  
  43. console.log(pAdd4(2,4))
  44. console.log(pAdd4(2))
  45. console.log(pAdd4(3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement