【问题标题】:How to combine map and clamp function together如何将地图和钳制功能结合在一起
【发布时间】:2021-12-27 08:44:44
【问题描述】:

有两个功能

const clamp = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a) + c

const c = map(-50, 0, 1, 0, 100)
const _c = clamp(c, 0, 1)
console.log(_c, c)

有什么办法可以将这两个功能结合起来,比如

const _c = map(-50, 0, 1, 0, 100, {clamp: true})

这样我就不需要从 map 函数中复制参数来获取参数范围内的新值。

【问题讨论】:

    标签: javascript function


    【解决方案1】:

    这很简单,只需创建一个函数并按顺序执行原始映射函数,如果clamp 参数为true,则计算并返回它。检查下面的代码。

    const map(x, a, b, c, d, clamp) {
       const map_result = (x - a) * (d - c) / (b - a) + c;
       if (clamp) {
           const clamp_result = Math.max(Math.min(map_result, Math.max(a, b)), Math.min(a, b));
           return clamp_result
       }
    
       return map_result;
    }
    

    你可以这样使用它: const _c = map(-50, 0, 1, 0, 100, true)

    【讨论】:

      【解决方案2】:

      您可以将函数传递给clamp 函数并在其中使用它。或者如果函数在同一个位置,你可以在clamp函数中调用它

      const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a) + c
      
      
       
      const _map = (x, a, b, c, d, map) =>  Math.max(Math.min(map(x, a, b, c, d), Math.max(a, b)), Math.min(a, b));
      
      
      const a =  _map(-50, 0, 1, 0, 100, map)
      console.log(a)

      【讨论】:

        猜你喜欢
        • 2019-06-12
        • 2011-05-07
        • 2017-10-01
        • 2019-10-05
        • 2016-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多