【问题标题】:How can I optimize my function not to repeat lines?如何优化我的功能不重复行?
【发布时间】:2019-08-10 01:30:07
【问题描述】:

我正在做我的项目并决定最大限度地优化它!我的函数的目的是随机放置一张图片。

这是我的 js 函数:

moveImage() {
  this.imgTop = Math.round(Math.random() * (screen.height - this.imgHeight));
  this.imgLeft = Math.round(Math.random() * (screen.width - this.imgWidth));
}

可以优化吗? 我不认为我应该使用 random 两次...

【问题讨论】:

  • “我不认为我应该使用 random 两次...” 为什么不呢?你不想要不同的数字吗?
  • 您是要优化性能还是优化可读性?在这两个方面似乎已经非常接近最优了。如果您不想调用Math.random 两次,您总是可以将结果存储在一个变量中,但这会导致非常不同的行为,因此请仔细考虑这是否是您真正想要的。
  • @T.J.Crowder 我正试图找到一些变体来少写......因为这个原因!数字应该不同
  • moveImage(img, screensize, size) { img = Math.round(Math.random() * (screensize - size)); } moveImage(this.imgTop, screen.height, this.imgHeight) moveImage(this.imgLeft, screen.width, this.imgWidth)

标签: javascript function optimization ecmascript-6


【解决方案1】:

你的意思是这样的:

  const offset = ( available, size ) => Math.round(Math.random() * ( available - size ));

  moveImage() {
    this.imgTop = offset( screen.height, this.imgHeight );
    this.imgLeft = offset( screen.width, this.imgWidth );
  }

你只是把重复的部分放到了它自己的函数中?

包括对偏移函数的调用,这实际上可能归结为比原来更多的字符,因此不确定您自己的代码是否“过于重复”而无法开始。

编辑。或者更紧凑:

  const offset = range => Math.round(Math.random() * range);

  moveImage() {
    this.imgTop = offset( screen.height - this.imgHeight );
    this.imgLeft = offset( screen.width - this.imgWidth );
  }

【讨论】:

  • const offset = (range) => Math.round(Math.random() * range); ... offset( screen.height - this.imgHeight ); -- 在不进入代码高尔夫领域的情况下再删减几个字符。
猜你喜欢
  • 2018-08-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多