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

Ik-12 Chubko Mykhailo labwork6 Tasks 1 to 2 #24

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
12 changes: 11 additions & 1 deletion Exercises/1-pipe.js
Original file line number Diff line number Diff line change
@@ -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 };
28 changes: 27 additions & 1 deletion Exercises/2-compose.js
Original file line number Diff line number Diff line change
@@ -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 };