Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 250
Tutan Ramen Avatar asked Oct 13 '16 03:10

Tutan Ramen


5 Answers

You can partially apply replace with a Regex that runs toUpper on the first character:

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

like image 117
lax4mike Avatar answered Nov 20 '22 01:11

lax4mike


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);
like image 20
zerkms Avatar answered Nov 20 '22 01:11

zerkms


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)

like image 25
Christian Bankester Avatar answered Nov 20 '22 02:11

Christian Bankester


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'
like image 5
davidchambers Avatar answered Nov 20 '22 02:11

davidchambers


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'
like image 1
Nicolás Fantone Avatar answered Nov 20 '22 00:11

Nicolás Fantone