Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. const compose = (f, g) => x => f(g(x));
  2.  
  3. const fold = f => acc => xs => {
  4. if (xs.length < 1) return acc;
  5. return fold(f)(f(xs[0], acc))(xs.slice(1));
  6. }
  7.  
  8. const fold2 = acc => f => fold(f)(acc);
  9.  
  10. const map = compose(fold2([]), f => (x, y) => y.concat(f(x)));
  11.  
  12. const filter = compose(fold2([]), f => (x, y) => f(x) ? y.concat(x) : y);
  13.  
  14. const generate = s => e => {
  15. if (s > e) return [];
  16. return [s].concat(generate(s + 1)(e));
  17. }
  18.  
  19. const countup = generate(1);
  20.  
  21. const multiply = (...args) => {
  22. if (args.length < 1) return 1;
  23. return args[0] * multiply(...args.slice(1));
  24. }
  25.  
  26. const NegativeNumberError = new Error('Only integers 0 and above are allowed!');
  27.  
  28. const fact = compose(compose(fold(multiply)(1), countup), n => {
  29. if (n >= 0) return n;
  30. throw NegativeNumberError;
  31. });
  32.  
  33. const expect = (fn, expectedValue, isCurried, ...args) => {
  34. const isSame = (x, y) => x.toString() === y.toString();
  35.  
  36. const applyToCurried = (fn, ...args) => {
  37. if (args.length < 2) return fn(args[0]);
  38. return applyToCurried(fn(args[0]), ...args.slice(1));
  39. }
  40.  
  41. try {
  42. if (isCurried) return isSame(applyToCurried(fn, ...args), expectedValue);
  43. return isSame(fn(...args), expectedValue)
  44. } catch (err) {
  45. return err === expectedValue;
  46. }
  47. }
  48.  
  49. // Test functions
  50. console.log(expect(fact, 120, false, 5));
  51. console.log(expect(fact, 1, false, 0));
  52. console.log(expect(fact, NegativeNumberError, false, -1));
  53. console.log(expect(map, [2,4,6,8,10], true, x => x * 2, countup(5)));
  54. console.log(expect(filter, generate(5)(10), true, x => x > 4, countup(10)));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement