使用 Ramda 实现的无参风格大写函数

11
5个回答

16

您可以部分应用 replace 函数,并使用运行于第一个字符上的 toUpper 正则表达式:

const capitalize = R.replace(/^./, R.toUpper);


3
我进行了一些快速且不太精确的基准测试,并发现您的答案是最快的。 - Christian Bankester
replace 的第二个参数是一个字符串而不是一个函数。对我来说没有用。 - Damian Green
@DamianGreen Ramda使用本地JavaScript字符串方法实现了R.replace。第二个参数也可以是一个函数,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Syntax。 - lax4mike

14

它会是这样的:

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);

作为后续问题,当使用点式风格编写时,您将如何处理空值情况?如果使用 capitalize(null) 调用此函数,则会抛出异常。 - Tutan Ramen
@TutanRamen 在其前面加上 ifElse(equals(null), identity, ,否则我认为这就是使用 Maybe monad 的地方。 - zerkms
太棒了!现在甚至可以使用isNil代替equals(null)了! - tmikeschu
3
使用unless函数可以取代ifElseidentity的组合,这样可能更易于阅读。具体做法是:const capitalizeIfNotNil = R.unless(R.isNil, capitalize); - Nicolás Fantone

5

我建议使用R.lens

const char0 = R.lens(R.head, R.useWith(R.concat, [R.identity, R.tail]));

R.over(char0, R.toUpper, 'ramda');
// => 'Ramda'

4
我为有兴趣的人准备了一些快速且简单的基准测试。看起来@lax4mike提供的答案是最快的(尽管更简单的非Point-Free str[0].toUpperCase() + str.slice(1) 更快[但这也不是OP所要求的,所以无关紧要])。 https://jsfiddle.net/960q1e31/ (您需要打开控制台并运行该Fiddle才能查看结果)

1

如果有人正在寻找一个将第一个字母大写并且同时将其他字母小写的解决方案,那么这里就是:

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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接