- I have to implement function pipe.
- The function is supposed to accept value and a sequence of functions.
- Each function should operate on the provided value and pass the output to the other function in a sequence.
- If the provided argument is not a function, pipe should immediately throw an error and stop the execution.
- Use function isFunction and if it gives false, throw an error.
This is what I have so far:
function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}
////////////////// Implementing pipe function ////////////////////
const pipe = (value, ...funcs) => {
try {
const result = funcs.reduce(function (acc, currFunc) {
if (isFunction(currFunc) === false)
throw new ('Provided argument at position 2 is not a function!');
return currFunc(acc);
}, value);
return result;
} catch (err) {
return err.message;
}
};
///////////////////////////////////////////////////////////////
const replaceUnderscoreWithSpace = (value) => value.replace(/_/g, ' ');
const capitalize = (value) =>
value
.split(' ')
.map((val) => val.charAt(0).toUpperCase() + val.slice(1))
.join(' ');
const appendGreeting = (value) => `Hello, ${value}!`;
const error = pipe('john_doe', replaceUnderscoreWithSpace, capitalize, '');
alert(error); // Provided argument at position 2 is not a function!
const result = pipe('john_doe', replaceUnderscoreWithSpace, capitalize, appendGreeting);
alert(result); // Hello, John Doe!
I couldn’t find the solution. Probably somebody could help me. Thanks in advance.