[英]Point-free style capitalize function with Ramda
虽然编写大写函数是微不足道的,但是:
“你好”=>“你好”“你好”=>“你好”
如何使用Ramda JS使用无点样式编写它?
它会是这样的:
const capitalize = R.compose(
R.join(''),
R.juxt([R.compose(R.toUpper, R.head), R.tail])
);
演示 (在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);
您可以使用在第一个字符上运行toUpper
的正则表达式部分应用replace
:
const capitalize = R.replace(/^./, R.toUpper);
我建议使用R.lens
:
const char0 = R.lens(R.head, R.useWith(R.concat, [R.identity, R.tail]));
R.over(char0, R.toUpper, 'ramda');
// => 'Ramda'
我为任何感兴趣的人整理了一些快速而肮脏的基准。 看起来@ lax4mike是提供答案中最快的(虽然更简单,非点无str[0].toUpperCase() + str.slice(1)
更快[并且也不是OP所要求的,所以这是没有实际意义])。
https://jsfiddle.net/960q1e31/ (您需要打开控制台并运行小提琴才能看到结果)
对于任何达到此目的的人来说,寻找一个大写第一个字母的解决方案, 并将其余字母缩小 ,这里是:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.