diff --git a/Exercises/1-pipe.js b/Exercises/1-pipe.js index 14e8909..f084ad4 100644 --- a/Exercises/1-pipe.js +++ b/Exercises/1-pipe.js @@ -1,5 +1,15 @@ 'use strict'; -const pipe = (...fns) => (x) => null; +const pipe = (...fns) => x => { + + for (const fn of fns) { + if (typeof fn !== 'function') { + throw new Error('All arguments must be functions'); + } + } + + + return fns.reduce((v, fn) => fn(v), x); + }; module.exports = { pipe }; diff --git a/Exercises/2-compose.js b/Exercises/2-compose.js index 8f8b77b..23f5cef 100644 --- a/Exercises/2-compose.js +++ b/Exercises/2-compose.js @@ -1,5 +1,31 @@ 'use strict'; -const compose = (...fns) => (x) => null; +const compose = (...fns) => { + const eventHandlers = {}; + const composedFn = (x) => { + if (fns.length === 0) return x; + let result = x; + try { + for (let i = fns.length - 1; i >= 0; i--) { + result = fns[i](result); + } + } catch (error) { + if (eventHandlers.error) { + eventHandlers.error.forEach(handler => handler(error)); + } + return undefined; + } + return result; + }; + + composedFn.on = (eventType, handler) => { + if (!eventHandlers[eventType]) { + eventHandlers[eventType] = []; + } + eventHandlers[eventType].push(handler); + }; + + return composedFn; +}; module.exports = { compose };