Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Вызов функции. (https://javascript.ru/forum/misc/82182-vyzov-funkcii.html)

OlesiaBOM 28.03.2021 11:44

Вызов функции.
 
Как записать функцию 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!

рони 28.03.2021 12:33

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!

voraa 28.03.2021 13:34

А так не проще?
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.