最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Point-free style capitalize function with Ramda - Stack Overflow

programmeradmin1浏览0评论

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?

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

Share Improve this question asked Oct 13, 2016 at 3:19 Tutan RamenTutan Ramen 1,2421 gold badge9 silver badges29 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 16

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 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'
发布评论

评论列表(0)

  1. 暂无评论