I have this working JavaScript function and I'm wondering if there could be a better way of achieving the same result.

我有这个有效的JavaScript函数,我想知道是否有更好的方法来实现相同的结果。

function factorise(number, factor){
    if(factor === 0) return 0;
    return Math.round(number / factor) * factor;
}

Now If I would want my randomly generated number that happend to be 100 to be divideable by 3 I could use this function.

现在,如果我希望我的随机生成的数字100可以被3除以,我可以使用这个函数。

factorise(100, 3); ---> 99

factorise(100,3); ---> 99

Here are some other examples:

以下是其他一些例子:

factorise(27, 5); ---> 25

factorise(27,5); ---> 25

factorise(2095, 27); ---> 1206

factorise(2095,27); ---> 1206

As you can see the returned values contain the factor of the factor number passed to the function. But my concern is the performance of this. Would it be ideal to have it run in physics of a JavaScript game engine? On top of that I'd really want to have a better name for the function.

如您所见,返回的值包含传递给函数的因子编号的因子。但我担心的是这种表现。让它在JavaScript游戏引擎的物理中运行是否理想?最重要的是,我真的希望有一个更好的名称功能。

2 个解决方案

#1


1

Probably that code is not your bottleneck. But here is an alternative which does not use floating-point division. It's 10 times faster on Firefox.

可能代码不是你的瓶颈。但是这里有一个不使用浮点除法的替代方案。它在Firefox上快了10倍。

function factorise(number, factor) {
  if(factor === 0) return 0;
  var rem = number % factor;
  number -= rem;
  return 2*rem >= factor ? number+factor : number;
}
console.log(factorise(100, 3));   // 99
console.log(factorise(27, 5));    // 25
console.log(factorise(2095, 27)); // 2106

更多相关文章

  1. JavaScript 函数柯里化(参考《JavaScript模式》)
  2. js中匿名函数的写法
  3. mongojs的异步调用找到函数
  4. 在JavaScript中的for循环中调用异步函数
  5. Javascript学习之匿名函数与自执行详解
  6. 第三节(JavaScript 对象、日期,函数)
  7. 用javaScript编写的验证函数只运行一次?
  8. 无法从按钮onclick事件ASP.NET 4调用Javascript函数
  9. jQuery:执行一个函数AFTER toggleClass被执行

随机推荐

  1. 详解xml与Java之间的转换
  2. xml在powerbuilder中应用的代码示例
  3. 在asp下通过xml打包网站文件的方法
  4. Android开发中关于2个Xml合并问题的实例
  5. 在xml中写动画的实例详解
  6. 通过javascript xml xsl取值及数据修改第
  7. 分享如何订阅没有RSS输出的网站教程
  8. jscript和vbscript对XML元素属性进行操作
  9. 实例详解如何配置Web.xml
  10. 网卡多队列技术与RSS功能的详细介绍