From 9da3919ca34eb6b38749e3fd674cd77558c4de88 Mon Sep 17 00:00:00 2001 From: Ovsky Aleksander Date: Mon, 23 Dec 2019 17:06:22 +0200 Subject: [PATCH] Task 1 and 2. In two task question. If I replaced "const f = x =>" on "const f = function( x )". May I use operator this in "Object.assign(f, { on })"? --- Exercises/1-pipe.js | 7 ++++++- Exercises/2-compose.js | 25 ++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/Exercises/1-pipe.js b/Exercises/1-pipe.js index d09882a..0107e2c 100644 --- a/Exercises/1-pipe.js +++ b/Exercises/1-pipe.js @@ -1,5 +1,10 @@ 'use strict'; +const pipe = (...fns) => { + if (!fns.reduce((g, f) => typeof f === 'function' && g, true)) { + throw new Error('Not a function'); + } -const pipe = (...fns) => x => null; + return g => fns.reduce((g, f) => f(g), g); +}; module.exports = { pipe }; diff --git a/Exercises/2-compose.js b/Exercises/2-compose.js index 368e521..d52eace 100644 --- a/Exercises/2-compose.js +++ b/Exercises/2-compose.js @@ -1,5 +1,28 @@ 'use strict'; -const compose = (...fns) => x => null; +const compose = (...fns) => { + const events = { }; + const emit = (event, ...args) => { + events[event](args); + }; + const f = x => { + let res = x; + try { + for (const f of fns.reverse()) { + res = f(res); + } + } catch (e) { + emit('error', e); + return undefined; + } + return res; + }; + + const on = (event, callback) => { + events[event] = callback; + }; + Object.assign(f, { on }); + return f; +}; module.exports = { compose };