首页 > 解决方案 > 按关键目标选择对象映射

问题描述

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

我认为这个片段说明了我需要什么:

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

标签: javascriptjavascript-objects

解决方案


正如我在评论中所描述的,智能数据结构和愚蠢的代码比其他方式更好地工作:

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 );


推荐阅读