我正在尝试编写一个将cm转换为feetinches的函数

cmToFtIn(30) === {"feet": 1, "inches": 0}
cmToFtIn(29) === {"feet": 0, "inches": 11}

我已经做的就是这个复杂的功能
const cmToFeetMultiplier = multiply(1/30.5)
const ftToInMultiplier = multiply(12)
const floor = (num) => Math.floor(num)
const round = (num) => Math.round(num)
const cmToFtIn = pipe(
   cmToFeetMultiplier,
   juxt([identity, floor]),
   juxt([identity, pipe(apply(subtract), ftToInMultiplier, round)]),
   flatten,
   cond([
     [pipe(nth(2), equals(12)), (d) => ({feet: d[1] + 1, inches: 0})],
     [always(true), (d) => ({feet: d[1], inches: d[2]})],
   ])
  )

也许有人对如何简化提出了一些建议?

Playground

最佳答案

当您用Google搜索“厘米为英寸”时:

javascript - 将厘米转换为英尺和英寸-LMLPHP

和“厘米到英尺”:

javascript - 将厘米转换为英尺和英寸-LMLPHP

然后,我们可以构建inchfoot函数:

const inch = flip(divide)(2.54);
const foot = flip(divide)(30.48);

inch(30); //=> 11.811023622047244
foot(30); //=> 0.984251968503937

如果需要从以厘米为单位的值返回对象{inch, foot},则可以不用Ramda:
const cmToFtIn = cm => ({inch: inch(cm), foot: foot(cm)});

cmToFtIn(30);
//=> {"foot": 0.984251968503937, "inch": 11.811023622047244}

与Ramda:
const cmToFtIn = applySpec({inch, foot});

cmToFtIn(30);
//=> {"foot": 0.984251968503937, "inch": 11.811023622047244}


我个人建议您不要直接从inchfoot函数返回舍入值。您可以在需要的地方应用第二遍将它们四舍五入。两种选择:

在您的Math.round对象上应用{inch, foot}:
map(Math.round, cmToFtIn(30));
//=> {"foot": 1, "inch": 12}

或组成Math.roundinch / foot函数:
const cmToFtIn = applySpec({
  inch: compose(Math.round, inch),
  foot: compose(Math.round, foot)
});

cmToFtIn(30);
//=> {"foot": 1, "inch": 12}

关于javascript - 将厘米转换为英尺和英寸,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57940949/

10-13 00:21