简体   繁体   中英

Point-free style capitalize function with Ramda

While writing a capitalize function is trivial, such that:

"hello" => "Hello" "hi there" => "Hi there"

How would one write it using point-free style using Ramda JS?

https://en.wikipedia.org/wiki/Tacit_programming

It would be something like that:

const capitalize = R.compose(
    R.join(''),
    R.juxt([R.compose(R.toUpper, R.head), R.tail])
);

Demo (in ramdajs.com REPL).

And minor modification to handle null values

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

I suggest using R.lens :

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

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

I put together some quick and dirty benchmarks for anyone interested. Looks like @lax4mike's is fastest of the provided answers (though the simpler, non-point-free str[0].toUpperCase() + str.slice(1) is way faster [and also not what OP was asking for, so that's moot]).

https://jsfiddle.net/960q1e31/ (You'll need to open the console and run the fiddle to see the results)

For anyone reaching this looking for a solution that capitalizes the first letter and also lowercases the rest of the letters , here it is:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM