javascript - 按关键目标选择对象映射
问题描述
给定一个数字,我需要知道它在哪个球门柱上。
我认为这个片段说明了我需要什么:
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
解决方案
正如我在评论中所描述的,智能数据结构和愚蠢的代码比其他方式更好地工作:
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 );
推荐阅读
- google-chrome-extension - 在跨多个来源运行内容脚本的 chrome 扩展中使用 auth0 (oauth2) 对用户进行身份验证的最佳方法是什么?
- haskell - 基于指令标记“fgl”图的边
- flutter - 在重建之间保持状态
- java - 即使满足等价条件/第一个 if 语句,程序也会重复用户输入
- google-cloud-bigtable - google cloud BigTable 有数据浏览器吗?
- java - 如何将 JSON 值添加到 Java 中的 ArrayList
- node.js - 使用自制程序更新 nodejs 困境:需要更多权限但 brew 不适用于 sudo?
- javascript - history.push 不会在 React/Typescript 中重新渲染/刷新组件
- javascript - console.log 输出到文档而不是控制台
- java - 测试 RestController 时模拟 liquibase:Spring + JPA + Junit Jupiter + liquibase