Cost Calculation Calculator

There are two sliders, the number of calls and the average duration of the call. There is a total cost of the call. The values of the sliders are in the input value. The base cost is 200. The bottom line is, if the value of the first slider is more than 3x, then let's say + 150 is added to the price, and if the value of the second slider is also more than 3x, then let's say + 130 is added to the cost. Total if both sliders have the value >=3 200+130+150 = 480. And if the value is higher than 7 then this figure is still let's say + 200 is added. I have already received the value of their input, but I do not know how to process such functionality and pass it to the input value of the total cost. Tell me with the implementation, please. (The noUiSlider slider, I couldn't load it here, so I wrote the value for input manually).

Author: w3cwhy, 2020-05-29

1 answers

With your library.

const startPrice = 200;
const firstInputStep = new Array( ['>=3', 150], ['>=7', 350] );
const secondInputStep = new Array( ['>=3', 200], ['>=7', 400] );

let firstSlider;
let secondSlider;
const price = document.getElementById('price');

init();
addListeners();
calculatePrice();

function init () {
  firstSlider = noUiSlider.create(document.getElementById('first-slider'), {
    start: [2],
    connect: true,
    tooltips: [true],
    step: 1,
    range: {
        'min': 0,
        'max': 50
    }
  });
  secondSlider = noUiSlider.create(document.getElementById('second-slider'), {
    start: [2],
    connect: true,
    tooltips: [true],
    step: 1,
    range: {
        'min': 0,
        'max': 50
    }
  });
}

function addListeners () {
  firstSlider.on('slide', calculatePrice);
  secondSlider.on('slide', calculatePrice);
}

function calculatePrice () {
  let firstValue = firstSlider.get();
  let secondValue = secondSlider.get();
  let finallyPrice = (typeof startPrice === 'number') ? startPrice : 0;
  finallyPrice += getStepByValue(firstInputStep, firstValue);
  finallyPrice += getStepByValue(secondInputStep, secondValue);
  price.innerText = `price: ${finallyPrice}`;
}

function getStepByValue (stepsMap, val) {
  let stepPrice = 0;
  val = Number.parseInt(val);
  if (typeof val === 'number') {
      for (let item of stepsMap) {
          if (eval(`${val}${item[0]}`)) {
              stepPrice = item[1];
          }
      }
  }
  return stepPrice;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.5.0/nouislider.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/14.5.0/nouislider.min.css" rel="stylesheet">
<div style="padding: 15px">
  <p>Slider 1:</p>
  <div id="first-slider"></div>
  <p>Slider 2:</p>
  <div id="second-slider"></div>
  <p>Price: </p>
  <div id="price"></div>
</div>
 2
Author: Владислав, 2020-05-29 17:44:27