我有一个正在转换的字符串:
"replace-me-correctly" => "Replace me correctly"
我的代码使用Ramda.js:
const _ = R; //converting Ramda.js to use _
const replaceTail = _.compose(_.replace(/-/g, ' '), _.tail);
const upperHead = _.compose(_.toUpper ,_.head);
const replaceMe = (str) => _.concat(upperHead(str) , replaceTail(str));
replaceMe("replace-me-correctly"); // "Replace me correctly"我想知道的是,是否有一种更干净、更有效的方法将replaceTail与upperHead结合起来,所以我只遍历了一次字符串?
JSBin实例
发布于 2015-11-27 01:56:13
不确定是否只遍历一次字符串。听起来很难。不过,我会提供一些不同的方法来寻找乐趣和洞察力。
函数的单核实例将通过使用给定的参数运行每个函数并将其结果连接起来(它们都必须返回相同的类型才能正确组合)。replaceMe正是这样做的,所以我们可以使用mconcat代替。
const { compose, head, tail, replace, toUpper } = require('ramda')
const { mconcat } = require('pointfree-fantasy')
// fun with monoids
const replaceTail = compose(replace(/-/g, ' '), tail)
const upperHead = compose(toUpper, head)
const replaceMe = mconcat([upperHead, replaceTail])
replaceMe("replace-me-correctly")
//=> "Replace me correctly"这是一种有趣的组合功能的方法。我不知道为什么要求在tail之前抢占replace。似乎可以通过regex更新replace函数以替换任何通过起始字符的-。如果是这样的话,我们可以内联replace。
还有一件事。dimap的功能实例非常简洁,镜片也是如此。使用它们,我们可以将字符串转换为数组,然后将toUpper仅转换为第0个索引。
const { curry, compose, split, join, head, replace, toUpper } = require('ramda')
const { mconcat } = require('pointfree-fantasy')
const { makeLenses, over } = require('lenses')
const L = makeLenses([])
// fun with dimap
const dimap = curry((f, g, h) => compose(f,h,g))
const asChars = dimap(join(''), split(''))
const replaceMe = compose(replace(/-/g, ' '), asChars(over(L.num(0), toUpper)))
replaceMe("replace-me-correctly")
//=> "Replace me correctly"发布于 2015-11-27 16:09:58
布莱恩的解决方案很棒。
请注意,您可以使用mconcat在普通Ramda中使用lift进行类似的操作。
const replaceMe = _.lift(_.concat)(upperHead, replaceTail)https://stackoverflow.com/questions/33948482
复制相似问题