JavaScript - 关于数据结构的问题

发布于 2024-09-02 01:41:04 字数 949 浏览 4 评论 0原文

我正在尝试根据积分系统计算某人的肠道健康状况。我可以以任何方式编辑数据结构或逻辑。我只是想编写一个函数和数据结构来处理这种能力。

伪计算器函数:

// Bowel health calculator
var points = 0;

If age is from 30 and 34:
    points += 1
If age is from 35 and 40:
    points += 2

If daily BMs is from 1 and 3:
    points -= 1
If daily BMs is from 4 and 6:
    points -= 2

return points;

伪数据结构:

var points_map = {
    age:
    {
        '35-40': 1,
        '40-45': 2,
        '45-50': 6,
        '50-55': 2,
        '55-60': 1,
        '60-65': 4,
        '65-70': 3,
        '70-75': 1,
        '75-150': 2
    },

    dbm:
    {
        '1-3': -1,
        '4-6': -2,
        '7-9': -3,
        '10-150': 5
    }

    // This plus about 10 more metrics like them (all with the same "Map a plus or minus value to each range" logic)
};

我有一个像这样的完整数据电子表格,我正在尝试编写代码的DRY版本和该数据的DRY版本(即,可能不是“30-34”的字符串)等)以便在没有大量 switch 语句的情况下处理此类事情。

I'm trying to calculate somebody's bowel health based on a points system. I can edit the data structure, or logic in any way. I'm just trying to write a function and data structure to handle this ability.

Pseudo calculator function:

// Bowel health calculator
var points = 0;

If age is from 30 and 34:
    points += 1
If age is from 35 and 40:
    points += 2

If daily BMs is from 1 and 3:
    points -= 1
If daily BMs is from 4 and 6:
    points -= 2

return points;

Pseudo data structure:

var points_map = {
    age:
    {
        '35-40': 1,
        '40-45': 2,
        '45-50': 6,
        '50-55': 2,
        '55-60': 1,
        '60-65': 4,
        '65-70': 3,
        '70-75': 1,
        '75-150': 2
    },

    dbm:
    {
        '1-3': -1,
        '4-6': -2,
        '7-9': -3,
        '10-150': 5
    }

    // This plus about 10 more metrics like them (all with the same "Map a plus or minus value to each range" logic)
};

I have a full spreadsheet of data like this, and I am trying to write a DRY version of code and a DRY version of this data (ie, probably not a string for the '30-34', etc) in order to handle this sort of thing without a humongous number of switch statements.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

‖放下 2024-09-09 01:41:04

我认为更好的结构可能有这样的东西:

{
[35,1],
[40,2],
[45,6],
...
[150, null]
},

然后在上面做一个循环:

for (var i =0; i<points_map.age.length-1; i++)
 {
 if (val >= points_map.age[i][0] && val<points_map.age[i+1][0])
    points += points_map.age[i][1];
 }

如果需要的话,这可以变得更有效,但你明白了。

I'd think a better structure might have something like:

{
[35,1],
[40,2],
[45,6],
...
[150, null]
},

then do a loop on it:

for (var i =0; i<points_map.age.length-1; i++)
 {
 if (val >= points_map.age[i][0] && val<points_map.age[i+1][0])
    points += points_map.age[i][1];
 }

This could be made a little more efficient if needed but you get the idea.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文