Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a range of values like, for example, [0, 100] = [minValue, maxValue] and the number of bands, for example BANDS_NUMBER = 5. So I can obtain these bands:

[0 - 20]
[21 - 40]
[41 - 60]
[61 - 80]
[81 - 100]

Then I want to associate a scale value at each range:

i: 0   -->  [0 - 20]   -->  0.2
i: 1   -->  [21 - 40]  -->  0.4
i: 2   -->  [41 - 60]  -->  0.6
i: 3   -->  [61 - 80]  -->  0.8
i: 4   -->  [81 - 100] -->  1

This value is computed in this way: (i + 1) / BANDS_NUMBER where i is the index of a hypothetical loop.

Then I have an input n whose value is in range [minValue, maxValue] = [0, 100].

What I want is the scale value related to this number. So, for example, if:

n = 0  --> scaleValue = 0.2 
n = 10 --> scaleValue = 0.2 
n = 20 --> scaleValue = 0.2 
n = 35 --> scaleValue = 0.4
n = 68 --> scaleValue = 0.8 
n = 99 --> scaleValue = 1
...

How can I create a function like that? I imagine a function like that:

function map(n, minValue, maxValue, bandsNumber) {
  const scaleValue = ...
  return scaleValue
}

All the values here are examples, I want that all works with any other values.

I don't know how to do to that. I need some help...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could take a formula, which take the range and the slot and returns a normalized value.

Because of the range, which is a bit too long (the last value is included in the interval), you need a check for the last value and prevent getting the next value, outside of the wanted interval.

function normalize(min, max, bands, n) {
    return n === max
        ? 1
        : Math.floor(1 + ((n - min) / (max - min)) * bands) / bands;
}

// 0.2 0.2 0.4 0.4 0.8 1 1
console.log(...[0, 10, 20, 35, 68, 99, 100].map(normalize.bind(null, 0, 100, 5)));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...