B2B : JavaScript Basics and Projects - Part 1
As an Analytics Technical Consultant, you will come across many requests or tasks requiring a good/expert knowledge of JavaScript. With the B2B series on JavaScript, my aim is to refresh my JavaScript basics, but via projects. I will be creating small projects and try to explain my learnings. This blog post is aimed at creating a Calculator via JavaScript.
The project is emulated from the Calculator Source code by Vikas Lalwani @ Codepen. I picked this example because of its super helpful comments which is missing from many of the other similar applications that I tried to emulate. This outlines a very important aspect when writing a code: adding helpful comments so that any other developer can understand your logic is a great ability to inculcate and follow.
This is how the calculator looks like in my Codepen:
Here is the complete source code that is available in the Codepen above:
"use strict"
var input = document.getElementById('input'), //for input/output
number = document.querySelectorAll('.numbers div'), // for number button
operator = document.querySelectorAll('.operators div'), // for operator button
result = document.getElementById('result'), // for equal button
clear = document.getElementById('clear'), // for clear button
resultDisplayed = false; // flag for result
//adding a click event handler to number buttons
for(var i=0 ; i < number.length ; i++) {
number[i].addEventListener("click", function(e) {
//storing current input string and last char in a variable
var currentString = input.innerHTML;
var lastChar = currentString[currentString.length - 1];
//if result is not displayed continue adding
if(resultDisplayed === false){
input.innerHTML += e.target.innerHTML;
//if result is displayed and user pressed an operator, continue adding to the string for next operation
} else if (resultDisplayed === true && lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷"){
resultDisplayed = false;
input.innerHTML += e.target.innerHTML;
//if result is displayed and user pressed a number we clear the string and add the new input to start the operation
} else {
resultDisplayed = false;
input.innerHTML = "";
input.innerHTML += e.target.innerHTML;
}
});
}
//adding a click event handler to operator buttons
for (var i = 0 ; i < operator.length ; i ++) {
operator[i].addEventListener("click", function(e){
//storing current input string and last char in a variable
var currentString = input.innerHTML;
var lastChar = currentString[currentString.length -1];
// if last character entered is an operator, replace it with the currently pressed one
if(lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷" ) {
var newString = currentString.substring(0, currentString.length-1) + e.target.innerHTML;
input.innerHTML = newString;
} else if (currentString.length == 0) {
//if first key pressed is an operator, give a prompt to enter a number
console.log("enter a number first")
} else {
//else just add the operator pressed to the input
input.innerHTML += e.target.innerHTML;
}
});
}
//adding a click event handler to the result(=) button
result.addEventListener("click", function() {
//This is the string that will be processing , e.g. 45-32×63+45
var inputString = input.innerHTML;
//Forming an array of numbers based on the input string. For the above example the array will be [45,32,63,45]
var numbers = inputString.split(/\+|\-|\×|\÷/g);
//forming an array of operators. for above string it will be: operators = ["+", "+", "-", "*", "/"]
// first we replace all the numbers and dot with empty string and then split
//Forming an array of operators. For the above example the array will be [-, x, +]
//First we replace all the numbers and dot with empty string and then split
var operators = inputString.replace(/[0-9]|\./g, "").split("");
console.log("The entire input is: " + inputString);
console.log("The operators selected are: " + operators);
console.log("The numbers selected are: " + numbers);
console.log('---------------');
// We are now looping through the numbers array and doing one operation at a time.
// Based on the principle of Mathematics, we first divide, then multiply, then subtract and finally add
// As we move through the loop, we are altering the original numbers and operators array
// The final element remaining in the array will be the output
//The indexOf method to determine the index of our query
/*let groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami"]
let resultIndex = groceries.lastIndexOf("Eggs",0);
console.log(resultIndex); //1
*/
//The Splice method is a built-in method that helps to change the content of array by
//removing or replacing existing element with new ones
//we start with Division operator. We use indexOf method to find if the user has selected the division symbol
//IMP: A value of -1 means that the operator doesn't exist in the Operators array. We check if it exists
var divide = operators.indexOf("÷");
while (divide > 0) {
//we take the numbers operator and apply the splice() method
numbers.splice(divide, 2, numbers[divide] / numbers[divide + 1]);
operators.splice(divide, 1);
divide = operators.indexOf("÷");
}
var multiply = operators.indexOf("×");
while (multiply != -1) {
numbers.splice(multiply, 2, numbers[multiply] * numbers[multiply + 1]);
operators.splice(multiply, 1);
multiply = operators.indexOf("×");
}
var subtract = operators.indexOf("-");
while (subtract != -1){
numbers.splice(subtract, 2, numbers[subtract] - numbers[subtract + 1]);
operators.splice(subtract, 1);
subtract = operators.indexOf("-");
}
var add = operators.indexOf("+");
while (add != -1) {
numbers.splice(add, 2, parseFloat(numbers[add]) + parseFloat(numbers[add + 1]));
operators.splice(add, 1);
add = operators.indexOf("+")
}
//displaying the output
input.innerHTML = numbers[0];
//displaying the result
resultDisplayed = true;
});
//clearing the input when the C button is pressed
clear.addEventListener("click", function(){
input.innerHTML = "";
})
Some of the new methods that I learnt through the above exercises
The Splice method is a built-in method that helps to change the content of array by removing or replacing existing element with new ones
splice();
Array.splice(index, remove_count, item_list);
I will keep adding my learnings to this blog post
That is all for this blog post. Drop me a line at (ritesh)at(thelearningproject)dot(in).