Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complete all tasks #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Exercises/1-pipe.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
'use strict';

const pipe = (...fns) => x => null;
const pipe = (...fns) => {
const isValid = fns.every(fn => typeof fn === 'function');
if (!isValid) throw new Error('invalid args');
return x => fns.reduce((res, fn) => fn(res), x);
};

module.exports = { pipe };
22 changes: 21 additions & 1 deletion Exercises/2-compose.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
'use strict';

const compose = (...fns) => x => null;
const compose = (...fns) => {
const events = new Map();
const outputFn = x =>
fns.reduceRight((arg, fn, i, arr) => {
try {
return fn(arg);
} catch (e) {
arr.length = 0;
return outputFn.emit('error', e);
}
}, x);
outputFn.emit = (event, ...args) => {
const handlers = events.get(event);
if (handlers) handlers.forEach(fn => fn(...args));
};
outputFn.on = (event, handler) => {
const existsEvent = events.get(event);
existsEvent ? existsEvent.push(handler) : events.set(event, [handler]);
};
return outputFn;
};

module.exports = { compose };