对象图按关键目标选择

时间:2019-02-14 16:00:54

标签: javascript javascript-objects

给出一个数字,我需要知道它在哪个球门柱上。

我认为此片段说明了我的需求:

const breakPoints = {
  '>1104': 4,
  '830<1104': 3,
  '556<830': 2,
  '<556': 1
}

const calculateHowMany = ( currentSize, breakPoints ) => {
  ...
  ...
  return howMany
}

let A = calculateHowMany( 1200,  breakPoints ) // should be 4
let B = calculateHowMany( 920,  breakPoints ) // should be 3
let C = calculateHowMany( 300,  breakPoints ) // should be 1

1 个答案:

答案 0 :(得分:1)

正如我的评论中所述,智能数据结构和哑代码比其他方法更有效:

const breakpoints = [
  { "amount": 1, "min": 0, "max": 556 },
  { "amount": 2, "min": 556, "max": 830 },
  { "amount": 3, "min": 830, "max": 1104 },
  { "amount": 4, "min": 1104, "max": Infinity }
];

const calculateHowMany = ( currentSize, breakPoints ) => {
  return breakPoints.find( breakpoint => breakpoint.min <= currentSize && breakpoint.max > currentSize ).amount;
};

let A = calculateHowMany( 1200,  breakpoints ) // should be 4
let B = calculateHowMany( 920,  breakpoints ) // should be 3
let C = calculateHowMany( 300,  breakpoints ) // should be 1

console.log( A, B, C );