diff --git a/.eslintignore b/.eslintignore index b860b9a..c2658d7 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,2 +1 @@ -Exercises/ node_modules/ diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..544138b --- /dev/null +++ b/.prettierrc @@ -0,0 +1,3 @@ +{ + "singleQuote": true +} diff --git a/Exercises/1-pipe.js b/Exercises/1-pipe.js index 14e8909..fd9be12 100644 --- a/Exercises/1-pipe.js +++ b/Exercises/1-pipe.js @@ -1,5 +1,12 @@ 'use strict'; -const pipe = (...fns) => (x) => null; +const pipe = (...fns) => { + fns.forEach((fn) => { + if (typeof fn !== 'function') { + throw new Error('Type of fn is not a function'); + } + }); + return (x) => fns.reduce((v, f) => f(v), x); +}; module.exports = { pipe }; diff --git a/Exercises/2-compose.js b/Exercises/2-compose.js index 8f8b77b..4e62b82 100644 --- a/Exercises/2-compose.js +++ b/Exercises/2-compose.js @@ -1,5 +1,25 @@ 'use strict'; -const compose = (...fns) => (x) => null; +const compose = (...fns) => { + const handlers = []; + const fn = (x) => { + if (fns.length === 0) return x; + const last = fns.length - 1; + let res = x; + try { + for (let i = last; i >= 0; i--) { + res = fns[i](res); + } + } catch (error) { + res = undefined; + handlers.forEach((handler) => handler(error)); + } + return res; + }; + fn.on = (name, handler) => { + if (name === 'error') handlers.push(handler); + }; + return fn; +}; module.exports = { compose };