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
You can partially apply replace
with a Regex that runs toUpper
on the first character:
const capitalize = R.replace(/^./, R.toUpper);
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);
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)
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With