问题描述
const limitSize = (limit: number): ((str: string) => string) => {
return (str: string) => str.substring(0,limit)
}
const replaceNewLine = (replaceWith: string): ((str: string) => string) => {
return (str: string) => str.replace(/\n/g,replaceWith)
}
它们都返回可以应用于字符串的函数
如何将它们链接在一起,以便结果还返回可以应用于字符串的函数?
我是否缺少lodash实用程序?
解决方法
我认为您需要Lodash的flow功能或Ramda的pipe
function square(n) {
return n * n;
}
var addSquare = _.flow([_.add,square]);
addSquare(1,2);
// => 9
,
只需创建一个新的函数定义,如下所示:
const limitReplace = (limit: number,replaceWith: string): ((str: string) => string) => {
return str => replaceNewLine(replaceWith)(limitSize(limit)(str));
}
用作:
const input = "Hel\nlo W\norld\n";
const limitSixReplaceSpace = limitReplace(6," ");
const result = limitSixReplaceSpace(input); // Hel lo