Вызов функции.
Как записать функцию pipe, чтобы каждая из функций передавала выходные данные другой функции в последовательности?
function isFunction(functionToCheck) { return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]'; } const pipe = (value, ...funcs) => { }; 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! |
OlesiaBOM,
function isFunction(functionToCheck) { return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]'; } const pipe = (value, ...funcs) => { let [fun, ...f] = funcs, isFun = isFunction(fun); value = isFun ? fun(value) : 'error'; return isFun && f.length ? pipe(value, ...f) : value }; 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! |
А так не проще?
const pipe = (value, ...funcs) => { try { return funcs.reduce ((v, f) => f(v), value) } catch (err) { return err; } }; 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! |
Часовой пояс GMT +3, время: 13:20. |