使用 Ramda 的无点样式大写函数
Point-free style capitalize function with Ramda
虽然编写大写函数很简单,例如:
"hello" => "Hello"
"hi there" => "Hi there"
如何使用 Ramda JS 使用无点样式编写它?
会是这样的:
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
);
Demo(在 ramdajs.com REPL 中)。
和处理 null
值的小修改
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
);
const capitalizeOrNull = R.ifElse(R.equals(null), R.identity, capitalize);
我建议使用 R.lens
:
const char0 = R.lens(R.head, R.useWith(R.concat, [R.identity, R.tail]));
R.over(char0, R.toUpper, 'ramda');
// => 'Ramda'
您可以使用在第一个字符上运行 toUpper
的正则表达式部分应用 replace
:
const capitalize = R.replace(/^./, R.toUpper);
我为任何感兴趣的人整理了一些快速而粗略的基准。看起来 @lax4mike 是所提供答案中最快的(尽管更简单的非无点 str[0].toUpperCase() + str.slice(1)
更快 [而且也不是 OP 所要求的,所以没有实际意义])。
https://jsfiddle.net/960q1e31/(您需要打开控制台并 运行 fiddle 才能看到结果)
对于任何达到这个要求的人来说,寻找一个将第一个字母大写并且也将其余字母小写的解决方案,这里是:
const capitalize = R.compose(R.toUpper, R.head);
const lowercaseTail = R.compose(R.toLower, R.tail);
const toTitle = R.converge(R.concat, [capitalize, lowercaseTail]);
toTitle('rAmdA');
// -> 'Ramda'
虽然编写大写函数很简单,例如:
"hello" => "Hello" "hi there" => "Hi there"
如何使用 Ramda JS 使用无点样式编写它?
会是这样的:
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
);
Demo(在 ramdajs.com REPL 中)。
和处理 null
值的小修改
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
);
const capitalizeOrNull = R.ifElse(R.equals(null), R.identity, capitalize);
我建议使用 R.lens
:
const char0 = R.lens(R.head, R.useWith(R.concat, [R.identity, R.tail]));
R.over(char0, R.toUpper, 'ramda');
// => 'Ramda'
您可以使用在第一个字符上运行 toUpper
的正则表达式部分应用 replace
:
const capitalize = R.replace(/^./, R.toUpper);
我为任何感兴趣的人整理了一些快速而粗略的基准。看起来 @lax4mike 是所提供答案中最快的(尽管更简单的非无点 str[0].toUpperCase() + str.slice(1)
更快 [而且也不是 OP 所要求的,所以没有实际意义])。
https://jsfiddle.net/960q1e31/(您需要打开控制台并 运行 fiddle 才能看到结果)
对于任何达到这个要求的人来说,寻找一个将第一个字母大写并且也将其余字母小写的解决方案,这里是:
const capitalize = R.compose(R.toUpper, R.head);
const lowercaseTail = R.compose(R.toLower, R.tail);
const toTitle = R.converge(R.concat, [capitalize, lowercaseTail]);
toTitle('rAmdA');
// -> 'Ramda'