jQuery Quick Cube Root

by Sandeep Kumar

HTML

<div id="banner-message">
  <div id="divInput">
    <input type="text" id="inpValue" />
  </div>
  <button>Calculate Cube Root</button>
  <br />
  <span id="spanCubeRoot"></span>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

#divInput {
  padding: 5px;
  margin-bottom: 5px;
}

#spanCubeRoot {
  padding: 5px;
  margin-top: 5px;
}

JavaScript

// find elements
var button = $("button")

// handle click and add class
button.on("click", () => {
	var value = $("#inpValue").val();
  
  var cubeRoot = quickCubeRoot(value);
  
  console.log(cubeRoot);
  
   $("#spanCubeRoot").text(cubeRoot);
})

function quickCubeRoot(num) {
  
  var cubes_10 = {
      '0': 0,
      '1': 1,
      '8': 8,
     '27': 7,
     '64': 4,
    '125': 5,
    '216': 6,
    '343': 3,
    '512': 2,
    '729': 9
  };
  
  // get last 3 numbers and the remaining numbers
  var arr = num.toString().split('');
  var last = arr.slice(-3);
  var first = parseInt(arr.slice(0, -3).join(''));
  
  // answer will be stored here
  var lastDigit = 0, firstDigit = 0, index = 0;
  
  // get last digit of cube root
  for (var i in cubes_10) {
    if (index === parseInt(last[last.length-1])) { lastDigit = cubes_10[i]; }
    index++;
  }
  
  // get first digit of cube root
  index = 0;
  for (var i in cubes_10) {
    if (parseInt(i) <= first) { firstDigit = index; }
    index++;
  }
  
  // return cube root answer
  return firstDigit + '' + lastDigit;
  
}