Recently took on the challenge of trying to solve all of the 10 Days Of JavaScript within one night to challenge myself:
I wanted to show how I solved each one within a short amount of time, that way you can use this as a reference.
Before We Start
There is a lot of material to cover, so I’ll try and go through each as fast as possible, that way you’ll have time to read the entire article.
Lessons
Day 0: Hello, World!
Link: Day 0: Hello World
Problem
- Function receives a string (“Welcome to 10 Days of JavaScript!”)
- Output via console log “Hello, World!” and then on the next line the string.
Solution
Solution here is quite simple with console.log.
function greeting(parameterVariable) {
console.log('Hello, World!');
console.log(parameterVariable);
}
Output
// parameterVariable = "Welcome to 10 Days of JavaScript!";Hello, World!
Welcome to 10 Days of JavaScript!
Day 0: Data Types
Link: Day 0: Data Types
Problem
- Function receives an integer, a float, and a string
- The function has a constant integer of 4
- The function has a constant float of 4.0
- The function has a constant string of “HackerRank”
- Console log the sum of the constant integer and the integer received
- Console log the sum of the constant float by the float received
- Console lot the constant string following the string received on one line
Original Code
function performOperation(secondInteger, secondDecimal, secondString) {
const firstInteger = 4;
const firstDecimal = 4.0;
const firstString = 'HackerRank ';
// write code below
}
Solution
The only thing I added to this is to validate the value at the end by parsing it as either an integer or a float to make sure the type comes out correctly.
function performOperation(secondInteger, secondDecimal, secondString) {
const firstInteger = 4;
const firstDecimal = 4.0;
const firstString = 'HackerRank ';
// write code below
console.log((firstInteger + parseInt(secondInteger, 0))); console.log((firstDecimal + parseFloat(secondDecimal, 2))); console.log(`${firstString}${secondString}`);
}
Output
// secondInteger = 5
// secondDecimal = 4.5
// secondString = "from Medium";9
8.5
HackerRank from Medium
Day 1: Arithmetic Operators
Link: Day 1: Arithmetic Operators
Problem
- A length and width are sent to two different functions
- getArea must return the area of the shape dimensions sent
- getPerimeter must return the perimeter of the shape dimensions sent
- Complete the functions
Original Code
function getArea(length, width) {
let area;
// Write your code here
return area;
}function getPerimeter(length, width) {
let perimeter;
// Write your code here
return perimeter;
}
Solution
I’m going to provide two solutions for this for the sake of optimizing the code footprint.
Solution 1
function getArea(length, width) {
let area;
// Write your code here
area = length * width; return area;
}
function getPerimeter(length, width) {
let perimeter;
// Write your code here
perimeter = 2 * (length + width); return perimeter;
}
Solution 2: Optimized
const getArea = (length, width) => (length * width);const getPerimeter = (length, width) => (2 * (length + width));
Output
// 3
// 4.513.5
15// 5
// 44.5222.5
99
Day 1: Functions
Link: Day 1: Functions
Problem
- A integer of value n is provided
- 1 ≤ n ≤ 10
- Output the factorial value of n (n!, 4! = 4 x 3 x 2 x 1 = 24)
Solution
This can be written is a few different ways, but let’s solve it with a for loop by decreasing the value until it reaches 1;
function factorial(n) {
let result = n;
for (var i = 1; i < n; i++) {
result = result * (n - i);
}
return result;
}
Output
// 0
0// 1
1 // 4
24// 6
730
Day 1: Let and Const
Link: Day 1: Let and Const
Problem
- A float value r is provided for the radius
- 0 < r ≤ 100
- Print (console.log) the area of the circle (π x r²)
- Print (console.log) the perimeter of the circle (2πr)
- Do not overwrite the try and catch but make sure the code still works
Original Code
function main() {
// Write your code here. Read input using 'readLine()'
// and print output using 'console.log()'.
let r = parseFloat(readLine());
// Print the area of the circle:
// Print the perimeter of the circle: try {
// Attempt to redefine the value of constant variable PI
PI = 0;
// Attempt to print the value of PI
console.log(PI);
} catch(error) {
console.error("You correctly declared 'PI' as a constant.");
}
}
Solution
Given that the the title of this problem is called let and const, we can assume we need to use let and const somewhere. We can also see that PI is declared later in the try and catch, and we cannot modify it:
...
try {
// Attempt to redefine the value of constant variable PI
PI = 0;
// Attempt to print the value of PI
console.log(PI);
} catch(error) {
console.error("You correctly declared 'PI' as a constant.");
}
...
But we know that there is a catch, so the only way we can get the error caught is by giving it an error. Considering that const cannot be redeclared or overwritten, then we can use that to trigger the error when PI = 0.
function main() {
// Write your code here. Read input using 'readLine()'
// and print output using 'console.log()'.
let r = parseFloat(readLine());
const PI = Math.PI; // Print the area of the circle: // Print the perimeter of the circle: try {
// Attempt to redefine the value of constant variable PI
PI = 0;
// Attempt to print the value of PI
console.log(PI);
} catch(error) {
console.error("You correctly declared 'PI' as a constant.");
}
}
The next two outputs are just using the formulas, so the full solution should look like this:
function main() {
// Write your code here. Read input using 'readLine()'
// and print output using 'console.log()'.
let r = parseFloat(readLine());
const PI = Math.PI;
// Print the area of the circle:
console.log((PI * Math.pow(r, 2)));
// Print the perimeter of the circle:
console.log((2 * PI * r));
try {
// Attempt to redefine the value of constant variable PI
PI = 0;
// Attempt to print the value of PI
console.log(PI);
} catch(error) {
console.error("You correctly declared 'PI' as a constant.");
}
}
Output
// 2.6
Error: You correctly declared 'PI' as a constant.
21.237166338267002
16.336281798666924// 6
Error: You correctly declared 'PI' as a constant.
113.09733552923255
37.69911184307752
Day 2: Conditional Statements: If-Else
Link: Day 2: Conditional Statements: If-Else
Problem
- An integer value score is provided for a students test
- 0 ≤ score ≤ 30
- Given the following legend, return the respective grade
Legend
If 25 < score <= 30, then grade = A.
If 20 < score <= 25, then grade = B.
If 15 < score <= 20, then grade = C.
If 10 < score <= 15, then grade = D.
If 5 < score <= 10, then grade = E.
If 0 <= score <= 5, then grade = F.
Solution
We could technically use a switch statement but given the lesson we’ll use if and else with a default of F.
function getGrade(score) {
let grade = "F";
// Write your code here
if (score > 5 && score <= 10) {
grade = "E";
} else if (score > 10 && score <= 15) {
grade = "D";
} else if (score > 15 && score <= 20) {
grade = "C";
} else if (score > 20 && score <= 25) {
grade = "B";
} else if (score > 25 && score <= 30) {
grade = "A";
}
return grade;
}
Output
// -5
F
// 11
D// 30
A
Day 2: Conditional Statements: Switch
Link: Day 2: Conditional Statements: Switch
Problem
- A string is provided where its length is 1 ≤ s ≤ 100
- Given the following legend, return the correct value based on the first letter
Legend
First letter is a, e, i, o, or u = A.
First letter is b, c, d, f, or g = B.
First letter is h, j, k, l, or m = C.
First letter is n, p, q, r, s, t, v, w, x, y, z = D.
Solution
We can solve this with a switch state or with RegEx.
Solution 1
function getLetters(s) {
if (s.length < 1 || s.length > 100) {
return null;
}
switch(s.charAt(0).toLowerCase()) {
case "a":
case "e":
case "i":
case "o":
case "u":
return "A";
break;
case "b":
case "c":
case "d":
case "f":
case "g":
return "B";
break;
case "h":
case "j":
case "k":
case "l":
case "m":
return "C";
break;
default: // everything else
return "D";
break;
}
}
Solution 2: RegEx
function getLetter(s) {
if (s.length < 1 || s.length > 100) {
return null;
}
let letter = "D"; // default if (s[0].match(/(h|j|k|l|m)/)) {
letter = "C";
} else if (s[0].match(/(b|c|d|f|g)/)) {
letter = "B";
} else if (s[0].match(/(a|e|i|o|u)/)) {
letter = "A";
}
return letter;
}
Output
// asdf
A//
null// sdf
D// bsdf
B// hsdf
C
Day 2: Loops
Link: Day 2: Loops
Problem
- Given a string of s of any length
- Output, in order, the vowels of that string on each new line
- Right after, output, in order, the consonants of that string on each new line
// Example
javascriptloops// Output
a
a
i
o
o
j
v
s
c
r
p
t
l
p
s
Solution
This can be solve with for loops and/or array maps.
Solution 1
function vowelsAndConsonants(s) {
const vowels = 'aeiou'; // output vowels
for(let i = 0; i < s.length; i++) {
if (vowels.indexOf(s.charAt(i)) > -1) {
console.log(s.charAt(i));
}
} // output consonants
for(let i = 0; i < s.length; i++) {
if (vowels.indexOf(s.charAt(i)) < 0) {
console.log(s.charAt(i));
}
}
}
Solution 2: Array Map
function vowelsAndConsonants(s) {
const vowels = 'aeiou';
s = s.split(''); // convert to array // output vowels
s.map((i) => {
if (vowels.indexOf(i) > -1) {
console.log(i);
}
return i;
}); // output consonants
s.map((i) => {
if (vowels.indexOf(i) < 0) {
console.log(i);
}
return i;
});
}
Output
// javascriptloopsa
a
i
o
o
j
v
s
c
r
p
t
l
p
s
Day 3: Arrays
Link: Day 3: Array
Problem
- Receive n length array between 1 ≤ n ≤ 10
- 0 ≤ nums ≤ 100 as integers
- Return the second largest integer of the array
Solution
function getSecondLargest(nums) {
// get the largest number
const max = Math.max(...nums);
// filter out largest number
nums = nums.filter(i => i !== max);
// return new largest number
return Math.max(...nums);
}
Output
// 2 3 6 6 5
5
Day 3: Try, Catch, and Finally
Link: Day 3: Try, Catch, and Finally
Problem
- Expect a value of s of any type
- If it’s a string take it return the reverse
- If it’s not a string console log “s.split is not a function”
- Console.log the result of reversing or not reversing s
Solution
I’ve performed this with and without a try/catch.
Solution 1
function reverseString(s) {
try {
s = s.split('').reverse().join('');
} catch (e) {
console.log("s.split is not a function");
}
console.log(s);
}
Solution 2: Without Try/Catch
function reverseString(s) {
if (typeof s !== "string") {
console.log("s.split is not a function");
}
if (typeof s === "string") {
s = s.split('').reverse().join('');
}
console.log(s);
}
Output
// s = "asdf"
fdsa// s = 17
s.split is not a function
17
Day 3: Throw
Link: Day 3: Throw
Problem
- n number of values of a sent
- 1 ≤ n ≤ 5
- a number between -100 and 100
- a = 0, throw error “Zero Error”
- a < 0, throw error “Negative Error”
- a > 0, console log “YES”
Solution
We simply need to create two if statements to catch the specific conditions and throw a message.
function isPositive(a) {
let result = "YES"; if (a < 0) {
throw({ message: "Negative Error" });
} else if (a === 0) {
throw({ message: "Zero Error" });
}
return result;
}
Output
// 1
// 2
// 3YES
YES
YES// 2
// 0
// 6YES
Zero Error
YES// -1
// 20Negative Error
YES
Day 4: Create a Rectangle Object
Link: Day 4: Create a Rectangle Object
Problem
- a = length of rectangle
- b = width of rectangle
- Complete Rectangle function to be instantiated
- when length called return a
- when width called return b
- when perimeter called, return the result
- when area called, return the result
Solution
Knowing that our function is going to be instantiated as a new Object, we should expect that a and b are passed to it. We just need to complete the rest of the values (length, width, perimeter, and area).
// Solution
function Rectangle(a, b) {
this.length = a;
this.width = b;
this.perimeter = ((a * 2) + (b * 2));
this.area = a * b;
}// Given
function main() {
const a = +(readLine());
const b = +(readLine());
const rec = new Rectangle(a, b);
console.log(rec.length);
console.log(rec.width);
console.log(rec.perimeter);
console.log(rec.area);
}
Output
// 4
// 54
5
18
20
Day 4: Count Objects
Link: Day 4: Count Object
Problem
- n is the number of values given for x and y
- 5 ≤ n ≤ 10
- x equal a coordinate between 1 and 100
- y equal a coordinate between 1 and 100
- Return the index where the two coordinates are the same.
Solution
function getCount(objects) {
let counts = 0;
// iterate over array of objects
objects.map((item) => {
if (item.x === item.y) {
counts++;
}
return item;
});
return counts;
}
Output
// n = 5
// x,y = 1 1
// x,y = 2 3
// x,y = 3 3
// x,y = 3 4
// x,y = 4 52
Day 4: Classes
Link: Day 4: Classes
Problem
- A class called Polygon is initialized with an array with share sizes
- Create a JavaScript class that returns the perimeter of the shape, when .perimeter() is called
Solution
// Solution
class Polygon {
constructor(arr) {
this.arr = arr;
} perimeter () {
return this.arr.reduce((prev, next) => prev + next);
}
}// Given
const rectangle = new Polygon([10, 20, 10, 20]);
const square = new Polygon([10, 10, 10, 10]);
const pentagon = new Polygon([10, 20, 30, 40, 43]);console.log(rectangle.perimeter());
console.log(square.perimeter());
console.log(pentagon.perimeter());
Output
// Polygon([10, 20, 10, 20]);
60// Polygon([10, 10, 10, 10]);
40// Polygon([10, 20, 30, 40, 43]);
143
Day 5: Inheritance
Link: Day 5: Inheritance
Problem
- Create a class called Square that extends an existing class of Rectangle
- Add functionality to Rectangle to return the shapes area
Solution
// Solution
Rectangle.prototype.area = function () {
return (this.w * this.h);
}class Square extends Rectangle {
constructor(w) {
super(w, w);
}
}// Given
class Rectangle {
constructor(w, h) {
this.w = w;
this.h = h;
}
}
Output
// Rectangle(3, 4)
12// Square(3)
9
Day 5: Template Literals
Link: Day 5: Template Literals
Problem
- A function will receive literals and remaning expressions
- Convert the expressing into values a and p
- Return an array
- Index 0 = ((p — Math.sqrt((Math.pow(p, 2) — (16 * a)))) / 4)
Index 1 = ((p + Math.sqrt((Math.pow(p, 2) — (16 * a)))) / 4)
Solution
// Solution
function sides(literals, ...expressions) {
const [a, p] = expressions;return [
((p - Math.sqrt((Math.pow(p, 2) - (16 * a)))) / 4),
((p + Math.sqrt((Math.pow(p, 2) - (16 * a)))) / 4)
];
}// Given
const [x, y] = sides`The area is: ${s1 * s2}.\nThe perimeter is: ${2 * (s1 + s2)}.`;
Output
// 10
// 1410
14
Day 5: Arrow Functions
Link: Day 5: Arrow Functions
Problem
- an array of n length between 1 and 10 is received
- nums is the array with values between 1 and 100
- if a value of nums is even multiply it by 2
- if a value of nums is odd multiply it by 3
- return the modified array
Solution
function modifyArray(nums) {
return nums.map((i) => (i % 2 === 0) ? i * 2 : i * 3);
}
Output
// n = 5
// nums = 1 2 3 4 53 4 9 8 15
Day 6: Bitwise Operators
Link: Day 6: Bitwise Operators
Problem
- Given an integer of n between 2 and 1000
- Given an integer of k between 2 and n
- q is just the number of lines we read from the input
- n is the max number of sequential numbers as a non-repeating pattern that can exist
// Example
n = 5// a b
// 1 2
// 1 3
// 1 4
// 1 5
// 2 3
// 2 4
// 2 5
// 3 4
// 3 5
// 4 5
- a&b = bitwise AND
// Example
n = 5// a b a&b
// 1 2 1&2 = 0
// 1 3 1&3 = 1
// 1 4 1&4 = 0
// 1 5 1&5 = 1
// 2 3 2&3 = 2
// 2 4 2&4 = 0
// 2 5 2&5 = 0
// 3 4 3&4 = 0
// 3 5 3&5 = 1
// 4 5 4&5 = 4
- Find the largest number of the result of a&b that is < k
// Example
n = 5, k = 2// a b a&b
// 1 2 1&2 = 0
// 1 3 1&3 = 1
// 1 4 1&4 = 0
// 1 5 1&5 = 1
// 2 3 2&3 = 2
// 2 4 2&4 = 0
// 2 5 2&5 = 0
// 3 4 3&4 = 0
// 3 5 3&5 = 1
// 4 5 4&5 = 4// Result
1
Solution
To solve this we’ll need to find all the combinations of a and b, and keep track of which is the largest and still < k:
function getMaxLessThanK(n, k) {
let largest = 0;
for (let a = 1; a <= n; a++) {
for (let b = a + 1; b<= n; b++) {
let ab = (a&b); // get the value of a&b
// confirm that ab < k
// if greater than the largest, redefine largest
if (ab < k && ab > largest) {
largest = ab;
}
}
}
return largest;
}
Output
// n k
// 5 2
1
// n k
// 8 5
4
// n k
// 2 2
0
Day 6: JavaScript Dates
Link: Day 6: JavaScript Dates
Problem
- Receive a string value of dateString
- The format is in DD/MM/YYYY (10/11/2009)
- Return the name of the day (Sunday, Monday, Tuesday,…) based on the date
Solution
function getDayName(dateString) {
const days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
];
return days[(new Date(dateString)).getDay()];
}
Output
// 10/11/2009
Sunday// 11/10/2010
Wednesday
Day 7: Regular Expressions I
Link: Day 7: Regular Expressions I
Problem
- Receive a string of s which is greater than or equal to the length of 3
- Write a regular expression that validates the string
- The string must be in all lowercase with characters from a-z
- The string must start and end with a vowel
- Return a boolean of true or false if the string meets the requirements
Solution
// Solution
function regexVar() {
// \b validate as a word
// (a|e|i|o|u) validate vowels
// [a-z] validate lowercase letters
// {2,} validate minimal length of 2 plus the first letter
// \1 validate the first letter is the same at the end
// \b end word validation
let re = new RegExp(/\b(a|e|i|o|u)[a-z]{2,}\1\b/);
return re;
}// Given
function main() {
const re = regexVar();
const s = readLine();
console.log(re.test(s));
}
Output
// bcd
false// abcd
false// abcda
true// abcdo
false
Day 7: Regular Expressions II
Link: Day 7: Regular Expressions II
Problem
- Receive a string of s which is greater than or equal to the length of 3
- Write a regular expression that validates the string
- String starts with either (Mr., Mrs., Ms., Dr., or Er.)
- String doesn’t contain any spaces
- String contains on the letters a-z or A-Z
- Return a boolean of true or false if the string meets the requirements
Solution
// Solution
function regexVar() {
// (Mr\.|Mrs\.|Ms\.|Dr\.|Er\.) Word must start with either one
// . Match any characters except line breaks
// * Match 0 or more after this
// [a-zA-Z] any letters in the alphabet upper or lowercase
// $ ends with the preceding arguments [a-zA-Z]
// /g globally match
// m multiline match
const re = new RegExp(/(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.).*[a-zA-Z]$/gm);
return re;
}// Given
function main() {
const re = regexVar();
const s = readLine();
console.log(!!s.match(re));
}
Output
// Mr.X
true// Mrs.Y
true// Dr#Joseph
false// Er .Abc
false
Day 7: Regular Expressions III
Link: Day 7: Regular Expressions III
Problem
- Receive a string of s
- length of s ≥ 3
- s is a string that contains numbers and letters
- Write a regular expression that validates the string
- The expression must only output integer numbers
// Example 1
// 102, 1948948 and 1.3 and 4.5102
1948948
1
3
4
5// Example 2
// 1 2 31
2
3
- Write a function that outputs the integer values from the string
Solution
// Solution
function regexVar() {
// [0-9] accept only number
// + must be the same of 1 or more of [0-9]
// /g globally match
// m multiline match
const re = new RegExp(/[0-9]+/gm);
return re;
}// Given
function main() {
const re = regexVar();
const s = readLine();
const r = s.match(re);
for (const e of r) {
console.log(e);
}
}
Output
// 102, 1948948 and 1.3 and 4.5
102
1948948
1
3
4
5// 1 2 3
1
2
3
Day 8: Create A Button
Link: Day 8: Create A Button
Problem
- Given index.html, js/button.js, and css/button.css
- Create an html button with an id of btn
- btn must have the styling of: width 96px, height 48px, font-size 24px
- The default innerHTML of button is set to 0
- Create the interaction where when the button is clicked its internal value displayed is incremented
// Example
btn = 0// clicked 5 times
btn = 5
Solution
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/button.css" type="text/css">
<title>Button</title>
</head>
<body>
<button id="btn">0</button>
<script src="js/button.js" type="text/javascript"></script>
</body>
</html>
js/button.js
window.onload = () => {
const button = document.getElementById('btn');
button.addEventListener('click', (e) => {
const clicks = parseInt(e.currentTarget.innerText, 0) + 1;
e.currentTarget.innerText = clicks;
});
}
css/button.css
#btn {
display: block;
width: 96px;
height: 48px;
font-size: 24px;
}
Output
Day 8: Buttons Container
Link: Day 8: Buttons Container
Problem
- Given index.html, js/buttonsGrid.js, and css/buttonsGrid.css
- Create 9 html buttons with an id of btn1,btn2,btn3,.. btn9
- The buttons must be contained in a div with an id of btns
- btns must be a width of 75% of the document’s body
- Each button within btns must have a width of 30%
- Each button must be a height of 48px, and a font-size of 24px
- The buttons must be in a grid of 3 x 3 with sequential numbers starting from 1
// Example ---- ---- ----
| 1 | 2 | 3 |
---- ---- ----
| 4 | 5 | 6 |
---- ---- ----
| 7 | 8 | 9 |
---- ---- ----
- Every time the number 5 is clicked all the buttons around it rotate clockwise
// Example
---- ---- ----
| 1 | 2 | 3 |
---- ---- ----
| 4 | 5 | 6 |
---- ---- ----
| 7 | 8 | 9 |
---- ---- ----// Click 1 ---- ---- ----
| 4 | 1 | 2 |
---- ---- ----
| 7 | 5 | 3 |
---- ---- ----
| 8 | 9 | 6 |
---- ---- ----// Another Click ---- ---- ----
| 7 | 4 | 1 |
---- ---- ----
| 8 | 5 | 2 |
---- ---- ----
| 9 | 6 | 3 |
---- ---- ----
Solution
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/buttonsGrid.css" type="text/css">
<title>Buttons Grid</title>
</head>
<body>
<div id="btns">
<button id="btn1">1</button>
<button id="btn2">2</button>
<button id="btn3">3</button>
<button id="btn4">4</button>
<button id="btn5">5</button>
<button id="btn6">6</button>
<button id="btn7">7</button>
<button id="btn8">8</button>
<button id="btn9">9</button>
</div>
<script src="js/buttonsGrid.js" type="text/javascript"></script>
</body>
</html>
css/buttonsGrid.css
#btns {
display: block;
overflow: hidden;
width: 75%;
}#btns button {
display: block;
width: 30%;
float: left;
height: 48px;
font-size: 24px;
}
js/buttonsGrid.js
window.onload = () => {
const button5 = document.getElementById('btn5');
button5.addEventListener('click', () => {
// get all the values from the buttons
let arr = [
document.getElementById('btn1').innerText,
document.getElementById('btn2').innerText,
document.getElementById('btn3').innerText,
document.getElementById('btn6').innerText,
document.getElementById('btn9').innerText,
document.getElementById('btn8').innerText,
document.getElementById('btn7').innerText,
document.getElementById('btn4').innerText
];
// create new shifted array
arr = [
...arr.slice(arr.length - 1),
...arr.slice(0, arr.length - 1)
];
// assign new values to buttons
document.getElementById('btn1').innerText = arr[0];
document.getElementById('btn2').innerText = arr[1];
document.getElementById('btn3').innerText = arr[2];
document.getElementById('btn6').innerText = arr[3];
document.getElementById('btn9').innerText = arr[4];
document.getElementById('btn8').innerText = arr[5];
document.getElementById('btn7').innerText = arr[6];
document.getElementById('btn4').innerText = arr[7];
});
}
Output
Day 9: Binary Calculator
Link: Day 9: Binary Calculator
NOTE: This is the longest one, so there will be a lot of code. Also, the css interpreter from HackerRank doesn’t seem to validate 100%.
Problem
- Create a binary calculator that performs addition, subtraction, multiplication, and division
- Given index.html, js/binaryCalculator.js, and css/binaryCalculator.css
- Create 8 html buttons and one div to display the data:
// innerHTML id Description/Behavior
res Contains the result of button presses.
btns A button container that displays all eight
calculator buttons.
0 btn0 A button expressing binary digit 0.
1 btn1 A button expressing binary digit 1.
C btnClr A button to clear the contents of res.
= btnEql A button to evaluate the contents of the
expression in res.
+ btnSum A button for the addition operation.
- btnSub A button for the subtraction operation.
* btnMul A button for the multiplication operation.
/ btnDiv A button for the integer division operation.
- Styling needs to follow:
- body has a width of 33%.- res has a background-color of lightgray, a border that is solid, a height of 48px, and a font-size of 20px.- btn0 and btn1 have a background-color of lightgreen and a color of brown.
- btnClr and btnEql have a background-color of darkgreen and a color of white.
- btnSum, btnSub, btnMul, and btnDiv have a background-color of black, a color of red.
- All the buttons in btns have a width of 25%, a height of 36px, a font-size of 18px, margin of 0px, and float value left.
- Formulas need to follow the binary calculations:
// User enters 11011
11011// User presses +
11011+// User enters 1000
11011+1000// User presses =
100011
Solution
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/binaryCalculator.css" type="text/css">
<title>Binary Calculator</title>
</head>
<body>
<div id="res"></div>
<div id="btns">
<button id="btn0">0</button>
<button id="btn1">1</button>
<button id="btnClr">C</button>
<button id="btnEql">=</button>
<button id="btnSum">+</button>
<button id="btnSub">-</button>
<button id="btnMul">*</button>
<button id="btnDiv">/</button>
</div>
<script src="js/binaryCalculator.js" type="text/javascript"></script>
</body>
</html>
css/binaryCalculator.css
body {
width: 33%;
}
#res {
display: block;
font-size: 20px;
height: 48px;
background-color: lightgray;
border: 2px solid black;
box-sizing: border-box;
}#btns {
display: block;
overflow: hidden;
}#btns button {
display: block;
float: left;
width: 25%;
height: 36px;
font-size: 18px;
background: black;
color: red;
}#btns #btn0, #btns #btn1 {
background-color: lightgreen;
color: brown;
}#btns #btnClr, #btns #btnEql {
background-color: darkgreen;
color: white;
}
js/binaryCalculator.js
window.onload = () => {
let inputs = [];
let operator = ''; const displayRes = () => {
const res = document.getElementById('res'); let val1 = inputs[0];
let val2 = inputs[1] === undefined ? '' : inputs[1]; res.innerText = `${val1}${operator}${val2}`;
}; const setOperator = op => {
if (inputs[1] === undefined) {
operator = op;
} displayRes();
}; const setValues = num => {
if (inputs.length === 0) {
inputs[0] = num;
} else if (inputs.length === 1 && operator.length === 0) {
inputs[0] += num;
} else if (inputs.length === 1 && operator.length > 0) {
inputs[1] = num;
} else if (inputs.length === 2 && operator.length > 0) {
inputs[1] += num;
} displayRes();
}; const btn0 = document.getElementById('btn0');
btn0.addEventListener('click', () => {
setValues('0');
}); const btn1 = document.getElementById('btn1');
btn1.addEventListener('click', () => {
setValues('1');
}); const btnSum = document.getElementById('btnSum');
btnSum.addEventListener('click', () => {
setOperator('+');
}); const btnSub = document.getElementById('btnSub');
btnSub.addEventListener('click', () => {
setOperator('-');
}); const btnMul = document.getElementById('btnMul');
btnMul.addEventListener('click', () => {
setOperator('*');
}); const btnDiv = document.getElementById('btnDiv');
btnDiv.addEventListener('click', () => {
setOperator('/');
}); const btnClr = document.getElementById('btnClr');
btnClr.addEventListener('click', () => {
inputs = [''];
operator = '';
displayRes();
}); const btnEql = document.getElementById('btnEql');
btnEql.addEventListener('click', () => {
if (inputs.length === 2 && operator.length > 0) {
let a = parseInt(inputs[0], 2);
let b = parseInt(inputs[1], 2); switch (operator) {
case '+':
inputs = [(a + b).toString(2)];
break;
case '-':
inputs = [(a - b).toString(2)];
break;
case '*':
inputs = [parseInt(a * b, 0).toString(2)];
break;
case '/':
inputs = [parseInt(a / b, 0).toString(2)];
break;
} operator = ''; displayRes();
}
});
};
Output
Get Your Badge
That’s it! If you followed all these tutorials, this is a “quick” way to get your badge for 10 Days Of JavaScript, which I highly recommend getting.
Final Thoughts
There were some things I would have love to see more of is explanation of concepts like classical vs prototype inheritance, the concept of OOP, fixing some links that were broken for the tutorials, and maybe even introducing composition vs inheritance.
All in all, it was great to get the experience, learn a few things, and challenge myself, although maybe over a few days instead of 1 night.
If you got value from this, please share it on twitter 🐦 or other social media platforms. Thanks again for reading. 🙏
Please also follow me on twitter: @codingwithmanny and instagram at @codingwithmanny.