Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to refactor an object with numeric values ​into a short size?

I need to display a specific number depending on the value of the slider. How can I refactor such code if I plan to increase the maximum value of the slider to 100. I think, writing an object such a long object is not the best solution.

const p = document.getElementById("price");
const result = document.getElementById("result");

const rangeObj = {
    0: 0,
  1: 0,
  2: 0,
  3: 1,
  4: 1,
  5: 1,
  6: 2,
  7: 2,
  8: 3,
  9: 3,
  10: 4,
  11: 4,
  12: 4,
  13: 5,
  14: 6,
  15: 6,
  16: 7,
  17: 7,
  18: 8,
  19: 8,
  20: 9
}

p.addEventListener("input", function() {
            console.log(p.value);
      result.innerText = rangeObj[p.value];
}, false); 
<input id="price" type="range" value="" max="20"  />

<div id="result"></div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could do something like this… I added a toNearest function it’ll round to the nearest value. In this case, I want all values to round to the nearest 5 (0-4 will produce a 0, 5-9 a 5, etc).

function toNearest(value, goal) {
  return Math.floor(value / goal) * goal;
}
const p = document.getElementById("price");
const result = document.getElementById("result");
const actual = document.getElementById("actual");

p.addEventListener("input", function() {
   const value = toNearest(p.valueAsNumber, 5);
   result.innerText = `Result: ${value}`;
   actual.innerText = `Actual: ${p.valueAsNumber}`;
}, false); 
<input id="price" type="range" value="" max="20"  />

<div id="result"></div>
<div id="actual"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading