Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const compose = (f, g) => x => f(g(x));
- const fold = f => acc => xs => {
- if (xs.length < 1) return acc;
- return fold(f)(f(xs[0], acc))(xs.slice(1));
- }
- const fold2 = acc => f => fold(f)(acc);
- const map = compose(fold2([]), f => (x, y) => y.concat(f(x)));
- const filter = compose(fold2([]), f => (x, y) => f(x) ? y.concat(x) : y);
- const generate = s => e => {
- if (s > e) return [];
- return [s].concat(generate(s + 1)(e));
- }
- const countup = generate(1);
- const multiply = (...args) => {
- if (args.length < 1) return 1;
- return args[0] * multiply(...args.slice(1));
- }
- const NegativeNumberError = new Error('Only integers 0 and above are allowed!');
- const fact = compose(compose(fold(multiply)(1), countup), n => {
- if (n >= 0) return n;
- throw NegativeNumberError;
- });
- const expect = (fn, expectedValue, isCurried, ...args) => {
- const isSame = (x, y) => x.toString() === y.toString();
- const applyToCurried = (fn, ...args) => {
- if (args.length < 2) return fn(args[0]);
- return applyToCurried(fn(args[0]), ...args.slice(1));
- }
- try {
- if (isCurried) return isSame(applyToCurried(fn, ...args), expectedValue);
- return isSame(fn(...args), expectedValue)
- } catch (err) {
- return err === expectedValue;
- }
- }
- // Test functions
- console.log(expect(fact, 120, false, 5));
- console.log(expect(fact, 1, false, 0));
- console.log(expect(fact, NegativeNumberError, false, -1));
- console.log(expect(map, [2,4,6,8,10], true, x => x * 2, countup(5)));
- console.log(expect(filter, generate(5)(10), true, x => x > 4, countup(10)));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement