30 Days Of JavaScript.7E
Day 7. Functions_Exercise
The exercises are all for writing codes by myself. I think the best thing of this course is that it provides a lot of exercise quizzes. Let’s start problem solving!
👟Level 1.
1) Declare a function fullName and it print out your full name.
function printFullName() {
let firstName = 'Jane';
let lastName = 'Doe';
let space = ' ';
let fullName = firstName + space + lastName;
return fullName;
}
printFullName(); //'Jane Doe'
console.log(printFullName()); //Jane Doe
I first declared a function without any parameter. If I just print the function using printFullName()
, the value is returned with single quotes. If I put console.log()
, it would just return the value.
2) Declare a function fullName and now it takes firstName, lastName as a parameter and it returns your full name.
function printFullName(firstName, lastName) {
return `${firstName} ${lastName}`;
}
console.log(printFullName('Jane', 'Doe'));
3) Declare a function addNumbers and it takes two parameters and it returns sum.
//function declaration
function addNumbers(numOne, numTwo) {
return numOne + numTwo;
}
console.log(addNumbers(7, 16));
//arrow funcition
const addNumbers = (numOne, numTwo) => numOne + numTwo;
console.log(addNumbers(5, 3));
4) An area of a rectangle is calculated as follows: area = length x width. Write a function which calculates areaOfRectangle.
//function declaration
function areaOfRectangle(length, width) {
return length * width;
}
//arrow function
const areaOfRectangle = (length, width) => length * width;
5) A perimeter of a rectangle is calculated as follows: perimeter= 2x(length + width). Write a function which calculates perimeterOfRectangle.
function perimeterOfRectangle(length, width) {
return 2 * length * width;
}
const perimeterOfRectangle = (length, width) => 2 * length * width;
6) A volume of a rectangular prism is calculated as follows: volume = length x width x height. Write a function which calculates volumeOfRectPrism.
function volumeOfRectPrism(length, width, height) {
return length * width * height;
}
const volumeOfRectPrism = (length, width, height) => length * width * height;
7) Area of a circle is calculated as follows: area = π x r x r. Write a function which calculates areaOfCircle.
//function declaration
function areaOfCircle(r) {
return Math.PI * r * r;
}
console.log(areaOfCircle(10)); //314.159265...
console.log(areaOfCircle(10).toFixed(0)); //314
//arrow function
const areaOfCircle = (r) => Math.PI * r * r;
If I want to round the number so that the number has no decimal number, I can use toFixed()
. Inside the parentheses I can put the number of decimal point that I want.
8) Circumference of a circle is calculated as follows: circumference = 2πr. Write a function which calculates circumOfCircle.
function circumOfCircle(r) {
return 2 * Math.PI * r;
}
const circumOfCircle = (r) => 2 * Math.PI * r;
9) Density of a substance is calculated as follows: density = mass/volume. Write a function which calculates density.
function density(mass, volume) {
return mass / volume ;
}
const density = (mass, volume) => mass / volume;
10) Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, speed.
function speed(distance, time) {
return distance / time ;
}
const speed = (distance, time) => distance / time;
11) Weight of a substance is calculated as follows: weight = mass x gravity. Write a function which calculates weight.
function weightOfObject(mass, gravity = 9.81) {
let weight = mass * gravity;
return weight;
}
const weightOfObject = (mass, gravity = 9.81) => mass * gravity;
12) Temperature in oC can be converted to oF using this formula: oF = (oC x 9/5) + 32. Write a function which convert oC to oF convertCelsiusToFahrenheit.
function convertCelsiusToFahrenheit(oC) {
let farenheit = (oC * 9/5) + 32;
return farenheit;
}
const convertCelsiusToFahrenheit = (oC) => (oC * 9/5) + 32;
13) Body mass index(BMI) is calculated as follows: bmi = weight in Kg / (height x height) in m2. Write a function which calculates bmi. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is underweight, normal, overweight or obese based the information given below.
- The same groups apply to both men and women.
- Underweight: BMI is less than 18.5
- Normal weight: BMI is 18.5 to 24.9
- Overweight: BMI is 25 to 29.9
- Obese: BMI is 30 or more
let yourBmi = (function calculateBmi() {
let weight = prompt('Enter your weight in Kg');
let height = prompt('Enter your height in M');
let bmi = weight / (height * height);
return bmi;
})();
switch (true) {
case yourBmi < 18.5 :
console.log('Underweight');
break;
case yourBmi < 24.9 :
console.log('Normal weight');
break;
case yourBmi < 29.9 :
console.log('Overweight');
break;
default:
console.log('Obese');
}
To use switch
to log various results depending on the BMI, I had to set a new variable to store the data of a function. About using switch, I once had similar quiz before at day 4.
I wanted the user to input the arguments, so I made a function without any parameters. And to make the function invoke itself without being called, I used self invoking functions, putting parentheses around the function. The function doesn’t need any parameters, so I just put empty parentheses after the parentheses around the function, to make it execute. If I don’t put another parentheses after the function it wouldn’t work.
In JavaScript, a “Self-Invoking” function is a type of function that is invoked or called automatically after its definition. The execution of such an anonymous function is done by enclosing it in a parenthesis set followed by another set of parenthesis.
14) Write a function called checkSeason, it takes a month parameter and returns the season : Autumn, Winter, Spring or Summer.
This one is similar to the previous task, but the function has to return the season, so I put switch()
inside the function.
(function checkSeason() {
let month = prompt('What month is it now?', 'Enter a number.');
switch (month) {
case '3': case '4': case '5':
console.log('Spring');
break;
case '6': case '7': case '8':
console.log('Summer');
break;
case '9': case '10': case '11':
console.log('Autumn');
break;
//same as case '12': case '1': case '2':
default:
console.log('Winter');
break;
}
})();
By the way, using pipe operator(||
) between each cases won’t work. The cases should be written separately. I can put an enter to each cases to make it more readable, but to shorten the code I just put multiple cases in one line.
(function checkSeason() {
let month = prompt('What month is it now?', 'Enter a number.');
if(month == '3' || '4' || '5') {
return 'Spring';
} else if (month == '6' || '7' || '8') {
return 'Summer';
} else if (month == '9' || '10' || '11') {
return 'Autumn';
} else {
return 'Winter';
}
})();
The upper code is what I’ve tried at first. I tried to shorten the code by using if else if else
, and put return
in the place of console.log()
. It wouldn’t work. No matter what number I put in, the result was always ‘Spring’.
I searched if there is a way of returning multiple values in a function. I found out the upper code wouldn’t work because the return
statement would stop the execution of the function. So basically the function always ended at the return 'Spring'
.
So I changed all the return
statement into console.log()
, but it didn’t work. It had the same problem as I had at this one. I realized that putting multiple values with the pipe operator won’t work. I changed the condition like below, and it worked.
(function checkSeason() {
let month = prompt('What month is it now?', 'Enter a number.');
if(month == '3' || month == '4' || month == '5') {
console.log('Spring');
} else if (month == '6' || month == '7' || month == '8') {
console.log('Summmer');
} else if (month == '9' || month == '10' || month == '11') {
console.log('Autumn');
} else {
console.log('Winter');
}
})();
15. Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum without using Math.max method.
function findMax(num1, num2, num3) {
if (num1 >= num2) {
if (num1 >= num3) {
console.log(num1);
} else {
console.log(num3);
}
} else {
if (num2 >= num3) {
console.log(num2);
} else {
console.log(num3);
}
}
}
console.log(findMax(5, -6, 9)); //9
To find the largest argument without using Math.max
method, I put a bunch of if else
in the function to manually compare the values of an argument. However, I thought there could be a better way. The code seemed unnecessaily long. After googling, I got an idea from stackoverflow.
function findMax(num1, num2, num3) {
const arr = [num1, num2, num3];
let maxNum = arr[0]
for (let i = 0; i < 3; i++) {
if (maxNum <= arr[i]) {
maxNum = arr[i]
}
}
return maxNum;
}
console.log(findMax(4, -30, 7)); //7
At first I wanted to somehow number the parameter like an index, but I couldn’t find out how. So, I made an array composed of three parameters, and used for loop
to run through each element of the array, compare the value, and replace the largest number(maxNum
) if there’s a larger number in the argument. Please comment below if you have any idea about improving my code!
I can expand the code into the case where there’s unlimited number of arguments, using arguments
object like below. I think using for loop
would be more efficient as the number of arguments increases.
function findMax() {
let maxNum = arguments[0];
for (let i = 0; i < arguments.length; i++) {
if (maxNum <= arguments[i+1]) {
maxNum = arguments[i+1]
}
}
return maxNum;
}
console.log(findMax(1, 5, -9, 70, 8, 64)); //70
First, I set the variable of largest number(maxNum
) to the first element of arguments. Then, the for loop
will run through each element of arguments, and for each loop the larger number would survive.
At first I set the condition `if (arguments[i] <= arguments[i+1])1, but it wouldn’t work the right way. To return the largest value from the argument, the number being compared should be the largest number, not the value before.
👟Level 2.
1) Linear equation is calculated as follows: ax + by + c = 0. Write a function which calculates value of a linear equation, solveLinEquation.
function solveLinEquation(a, b, c) {
x = prompt('What\'s the value of x?', 'Enter a number.');
y = -1 * ((a * x) + c) / b
return y;
};
solveLinEquation(2, -1, 5); //entered 1, returned 7
I wanted the user to put the x value after they set the linear equation by the arguments. With y
, I first tried ` ((a * x) + c) / (-1 * b) but it would return
NaN`. From now on I’ll multiply -1 at the numerator, at front.
I can also invoke the funtion without calling it by using self-invoking funtion like below. Using self-invoking function, I should put three parameters to get the function executed.
(function solveLinEquation(a, b, c) {
x = prompt('What\'s the value of x?', 'Enter a number.');
y = -1 * ((a * x) + c) / b
return y;
})(5, 1, 10); //entered 2, returned -20
2) Quadratic equation is calculated as follows: ax2 + bx + c = 0. Write a function which calculates value or values of a quadratic equation, solveQuadEquation.
When it comes to math, I should literally make a function that returns the value. I cannot just write the code like (a * x * x) + (b * x) + c = 0
and expect the function
to do everything. Here’s the site I looked up for.
function solveQuadEquation(a, b, c) {
if (a === undefined || b === undefined) {
return 0;
}
if (a != 0) {
x1 = ((-1 * b) + Math.sqrt((b * b) - 4 * a * c)) / (2 * a);
x2 = ((-1 * b) - Math.sqrt((b * b) - 4 * a * c)) / (2 * a);
if(x1 === x2) {
return x1;
} else {
return `${x1}, ${x2}`;
}
} else {
if (b != 0) {
let x = -1 * c / b;
return x;
} else {
return 0;
}
}
}
console.log(solveQuadEquation(1, 0, 0)); //0
console.log(solveQuadEquation()); //0
console.log(solveQuadEquation(4, 0, -4)); //1, -1
To return the value 0 when there’s no argument passed to the function, I used conditionals to sort out cases. If I remove first three lines of if
, the function returns Nan
if I don’t put any parameter. I first used console.log()
, but it also returned NaN
from the code below, so I used return
to stop the execution if the condition is met. Before that, I tried break
but it wouldn’t work.
break
is mostly used to exit loops.
At first I had a mistake of setting the condition using =
. Note that =
is an assignment operator. The equation operator should be ==
or ===
.
3) Declare a function name printArray. It takes array as a parameter and it prints out each value of the array.
//using 'join', return value as a string
function printArray(arr) {
return arr.join(', ');
}
const array = [1, 2, 3, 'four', 5];
console.log(printArray(array)); //1, 2, 3, four, 5
//using 'toString', return value as a string
function printArray(arr) {
return arr.toString();
}
const array = [1, 2, 3, 'four', 5];
console.log(printArray(array)); //1,2,3,four,5
//using 'for loop', print out each value
function printArray(arr) {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
const array = [1, 2, 3, 'four', 5];
printArray(array); //1 2 3 four 5
//using arrow function
const printArray = (arr) => {
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
}
printArray([1, 2, 3, 'four', 5]); //1 2 3 four 5
Using for loop
, return
instead of console.log()
didn’t work. It only returned the first value, because return
statement terminates the function. I can either set the array variable, or pass the array to the argument.
4) Write a function name showDateTime which shows time in this format: 08/01/2020 04:08 using the Date object.
function showDateTime() {
const now = new Date();
year = now.getFullYear();
month = now.getMonth();
date = now.getDate();
hours = now.getHours();
minutes = now.getMinutes();
if (month < 10) {
month = `0${month + 1}`
}
if (date < 10) {
date = `0${date}`
}
if (hours < 10) {
hours = `0${hours}`
}
if (minutes < 10) {
minutes = `0${minutes}`
}
timeFormat = `${month}/${date}/${year} ${hours}:${minutes}`
return timeFormat;
}
console.log(showDateTime()); //04/26/2022 16:45
5) Declare a function name swapValues. This function swaps value of x to y.
- First Approach (X)
function swapValues(x, y) {
x = y;
y = x;
return `${x}, ${y}`;
}
console.log(swapValues(3, 5)); //5, 5
The problem of this code above it that if we assign y to x at the first line of the function, the value at x disappears. So, I have to set a temporary variable to store the value.
- Final Approach (O)
function swapValues(x, y) {
let a = x;
x = y;
y = a;
console.log(`${x}, ${y}`);
}
swapValues(3, 5); //5, 3
6) Declare a function name reverseArray. It takes array as a parameter and it returns the reverse of the array (don’t use method).
function reverseArray(arr) {
const reversed = [];
for (let i = 0; i < arr.length; i++) {
reversed[i] = arr[i];
}
return reversed;
}
console.log([1, 2, 3, 4, 5]); //(5) [1, 2, 3, 4, 5]
Normally I would have used push
, but the quiz specifically asked not to, so I used for loop
and assigned each element to a new array.
7) Declare a function name capitalizeArray. It takes array as a parameter and it returns the capitalized array.
function capitalizeArray(arr) {
const capArr = [];
for (let element of arr) {
capArr.push(element.toUpperCase());
}
console.log(capArr);
}
capitalizeArray(['a', 'b', 'c', 'd', 'e']); //(5) ['A', 'B', 'C', 'D', 'E']
capitalizeArray(['apple', 'banana']); //
At first I declared a new array capArr
before the function. But as I continue putting arguments, the elements were keep added to the returned array. To fix it, I put the declaration of array below for loop
. But it also didn’t work because the capArr
would only be defined inside the for loop
. Finally, I put the capArr
in the place like above. Before writing a line of code, consider the scope, which is the range that certain value or variable would be used.
8) Declare a function name addItem. It takes an item parameter and it returns an array after adding the item.
const arr = [];
function addItem(item) {
arr.push(item);
console.log(arr);
}
addItem('olive'); //['olive']
addItem('sugar'); //(2) ['olive', 'sugar']
addItem('orange'); //(3) ['olive', 'sugar', 'orange']
Well, the mistake I made at the previous quiz was actually helping me on this one. If I want to set an array, and add an item to the array every time I call the function, I would just declare the array before the function.
I keep making mistake of just writing console.log()
, put argument inside the parentheses and wondering ‘why isn’t the function returning anything?’. Call the function by its name!
9) Declare a function name removeItem. It takes an index parameter and it returns an array after removing an item.
const arr = ['carrot', 'celery', 'mushroom', 'onion'];
function removeItem(item) {
//starting from the index of argument(item), remove one item
//it'll return the remaining array
arr.splice(arr.indexOf(item), 1);
console.log(arr);
}
removeItem('onion'); //(3) ['carrot', 'celery', 'mushroom']
removeItem('celery'); //(2) ['carrot', 'mushroom']
10) Declare a function name sumOfNumbers. It takes a number parameter and it adds all the numbers in that range.
function sumOfNumbers(min, max) {
sumAll = ((min + max) / 2 ) * (max - min + 1);
console.log(sumAll);
}
sumOfNumbers(5, 10); //45
11) Declare a function name sumOfOdds. It takes a number parameter and it adds all the odd numbers in that range.
function sumOfOdds(min, max) {
let oddSum = 0;
for (let i = min; i <= max; i++) {
if (i % 2 != 0) {
oddSum += i;
}
}
console.log(oddSum);
}
sumOfOdds(4, 9); //21
sumOfOdds(5, 9); //21
I modified the for loop
, to make it run from min
to max
, check if the number between that range is an odd number, and add that number to a new variable called oddSum
. I searched more about adding all the numbers in a range, and I think this stackoverflow site would help.
12) Declare a function name sumOfEvens. It takes a number parameter and it adds all the even numbers in that range.
function sumOfEvens(min, max) {
let evenSum = 0;
for (let i = min; i <= max; i++) {
if (i % 2 == 0) {
evenSum += i;
}
}
console.log(evenSum);
}
sumOfEvens(6, 15); //50
sumOfEvens(6, 14); //50
function sumOfEvens(min, max) {
let evenSum = 0;
for (let i = min; i <= max; i++) {
evenSum += i;
if (i % 2 != 0) {
continue;
}
}
}
sumOfEvens(6, 15); //50
sumOfEvens(6, 14); //50
13) Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
function evensAndOdds(num) {
let countOdd = 0;
let countEven = 0;
for (let i = 0; i <= num; i++) {
if (i % 2 == 0) {
countEven++;
} else {
countOdd++;
}
}
console.log(`Odd numbers: ${countOdd}, Even numbers: ${countEven}`)
}
evensAndOdds(30); //Odd numbers: 15, Even numbers: 16
I wanted to use continue
to skip counting either odd or even numbers, and the result is below. I think it’s more readable and efficient.
function evensAndOdds(num) {
let countOdd = 0;
for (let i = 0; i <= num; i++) {
if (i % 2 == 0) {
continue;
}
countOdd++;
}
console.log(`Odd numbers: ${countOdd}, Even numbers: ${num - countOdd + 1}`)
}
evensAndOdds(30); //Odd numbers: 15, Even numbers: 16
Using
continue
, I should put the statement before the actual execution of the function. If not, the code won’t be able to first filter the cases which it won’t execute.
14) Write a function which takes any number of arguments and return the sum of the arguments.
//using function declaration
function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
console.log(sum);
}
sumAll(6, 3, 7, 10); //26
To take ‘any number’ of arguments, I should declare a function with unlimited numbers of parameters, using the arguments
object. Be aware that the arguments
object has indexes like an array(though it’s not an array).
To use arguments
object, the parameter should be left empty when using function declaration. I first wrote ‘arguments’ in the parameter but it wouldn’t work.
const sumAll = (...args) => {
let sum = 0;
for (const element of args) {
sum += element;
}
console.log(sum);
}
sumAll(5, 20, 4, 9); //38
15) Write a function which generates a randomUserIp.
To generate a random user IP, four random numbers, each between 0 and 255, should be selected.
function randomUserIp() {
let userIp = [];
for (let i = 0; i < 4; i++) {
userIp[i] = Math.floor(Math.random() * 256);
}
console.log(userIp.join('.'));
}
randomUserIp(); //155.52.183.25
16) Write a function which generates a randomMacAddress.
The MAC address is a 12 digit hexadecimal number that is most often displayed with a colon or hypen separating every two digits (an octet), making it easier to read. So to generate a random MAC address, 12 hexadecimal numbers should be selected.
function randomMacAddress() {
let hexa = '0123456789abcdef';
const macAddress = [];
for (let i = 0; i < 6; i++) {
macAddress[i] = hexa.charAt(Math.floor(Math.random() * hexa.length)) + hexa.charAt(Math.floor(Math.random() * hexa.length));
}
console.log(macAddress.join('-'));
}
randomMacAddress(); //c0-17-c9-67-49-1d
To make it easier to separate the selected numbers by two digits, I joined two hexadecimal numbers into one element, using the addition operator(+) - since the type of selected character would be a string.
17) Declare a function name randomHexaNumberGenerator. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number.
console.log(randomHexaNumberGenerator());
'#ee33df'
This one had a similar idea to the quiz at Day 6. Hexadecimal numbers are composed with 16 symbols(0-9 and a-f). If there are ‘#’ in front of hexadecimal number, it means a color code.
function randomHexaNumberGenerator() {
const hexa = 'abcdef0123456789';
const randHexa = [];
for (let i = 0; i < 6; i++) {
randHexa[i] = hexa.charAt(Math.floor(Math.random() * 17));
}
console.log(`#${randHexa.join('')}`)
}
randomHexaNumberGenerator(); //#397a9e
I first set the variable randHexa
to []
, but I found out that sometimes 4 or 5 digits are returned by the function. So I changed the definition of an array, using Array()
.
const randHexa = Array(6);
It didn’t work, and it wasn’t the problem of setting an array. The number I multiplied at Math.random()
was wrong. hexa
has 16 characters, so the index would be from 0 to 15. If I multiply 17(which I thought was 16+1), there won’t be any character if Math.random()
picks 16. So I instead multiplied 16, which is (the max index number(15) + 1). Simply, I should just multiply the length of a string.
function randomHexaNumberGenerator() {
const hexa = 'abcdef0123456789';
const randHexa = [];
for (let i = 0; i < 6; i++) {
randHexa[i] = hexa.charAt(Math.floor(Math.random() * 16));
}
console.log(`#${randHexa.join('')}`)
}
randomHexaNumberGenerator(); //#e1f9d3
I should multiply
string.length
toMath.random()
to get random characters within the string.
18) Declare a function name userIdGenerator. When this function is called it generates seven character id. The function return the id.
console.log(userIdGenerator());
41XTDbE
function userIdGenerator() {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randomId = [];
for (let i = 0; i < 7; i++) {
randomId[i] = possible.charAt(Math.floor(Math.random() * possible.length));
}
console.log(randomId.join(''));
}
userIdGenerator(); //B3q3wLH
I wanted to find more useful way to set the possible characters, not listing it all. However after searching I couldn’t find a better way, so I kept it.
👟Level 3.
1) Modify the userIdGenerator function. Declare a function name userIdGeneratedByUser. It doesn’t take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated.
userIdGeneratedByUser()
'kcsy2
SMFYb
bWmeq
ZXOYh
2Rgxf
'
userIdGeneratedByUser()
'1GCSgPLMaBAVQZ26
YD7eFwNQKNs7qXaT
ycArC5yrRupyG00S
UbGxOFI7UXSWAyKN
dIV0SSUTgAdKwStr
'
function userIdGeneratedByUser() {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randomId = [];
let n = prompt('What number of characters do you want?');
for (let i = 0; i < n; i++) {
randomId[i] = possible.charAt(Math.floor(Math.random() * possible.length));
}
console.log(randomId.join(''));
}
function userIdGeneratedByUser() {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let numOfChars = prompt('What number of characters do you want?'); //6
let repeatFunc = prompt('What number of ids do you want to generate?'); //5
const randomId = [];
function generateId() {
for (let i = 0; i < numOfChars; i++) {
randomId[i] = possible.charAt(Math.floor(Math.random() * possible.length));
}
return randomId.join('');
}
const generatedIds = [];
for (let j = 0; j < repeatFunc; j++) {
generatedIds[j] = generateId();
}
console.log(generatedIds.join('\n'));
}
userIdGeneratedByUser();
/*
k00AmN
TrSu8d
yAHfg9
tSku3k
M8FBGv
*/
To repeat a function several times, I used for loop
to call the function. I set a new array called generatedIds
to store the returned value(id) from generateId
function. Using for loop, I assigned each ids from generateId
to a new array’s element.
Though I thought this code was kinda messy, because I put a function inside a function. So, in the code below I separated two functions and put the inner function above the main function. Then I called the generateId
function inside the userIdGeneratorByUser
.
I once read that a function should only do one job. I think separating two functions is the right way. It’s okay to set two separated functions because the first one doesn’t log the value on console. It just returns a value.
function generateId() {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randomId = [];
for (let i = 0; i < numOfChars; i++) {
randomId[i] = possible.charAt(Math.floor(Math.random() * possible.length));
}
return randomId.join('');
}
function userIdGeneratedByUser() {
let numOfChars = prompt('What number of characters do you want?');
let repeatFunc = prompt('What number of ids do you want to generate?')
const generatedIds = [];
for (let j = 0; j < repeatFunc; j++) {
generatedIds[j] = generateId();
}
console.log(generatedIds.join('\n'));
}
userIdGeneratedByUser();
At first I just moved the generateId
function above the main function. However, there was an error that the variables weren’t defined. A variable should be defined before being used.
Another thing to consider: I will only call the main function, which is userIdGeneratedByUser
, and I should be aware in what process the function would print out the value. If I put the prompt
at the upper function, the function keeps asking user each time in the for loop.
When the user call userIdGeneratedByUser
(in psuedo code):
- 1) Get the first input from the user(number of characters)
- 2) Get the second input from the user(number of ids)
- 3) Set an array to store the generated ids
- 4) Call the
generateId
function to define elements ingeneratedIds
array - 5) Generate id and return the value
- 6) Repeat 5), 6) through the
for loop
- 7) Log the
gneratedIds
array on console
2) Write a function name rgbColorGenerator and it generates rgb colors.
rgbColorGenerator()
rgb(125,244,255)
function rgbColorGenerator() {
const rgb = [];
for (let i = 0; i < 3; i++) {
rgb.push(Math.floor(Math.random() * 256));
}
//toString() will work the same as join()
console.log(`rgb(${rgb.join()})`);
}
rgbColorGenerator(); //rgb(217,117,191)
3) Write a function arrayOfHexaColors which return any number of hexadecimal colors in an array.
To make the function return any number of hexadecimal colors in the form of array, I decided to use prompt
to get the number from the user.
function generateHexaColor() {
const hexa = 'abcdef0123456789';
const randHexa = [];
for (let i = 0; i < 6; i++) {
randHexa[i] = hexa.charAt(Math.floor(Math.random() * 16));
}
return `#${randHexa.join('')}`;
}
function arrayOfHexaColors() {
let number = prompt('How many hexadecimal colors do you want?', 'Enter a number.'); //4
const hexaColors = [];
for (let i = 0; i < number; i++) {
hexaColors[i] = generateHexaColor();
}
console.log(hexaColors);
}
arrayOfHexaColors(); ////(4) ['#4590a2', '#c854dd', '#a0f7d2', '#b31f12']
One thing to notice is that I put return
at the inner function. If I put console.log()
instead, the returned value of that function(each element of the array) will also be logged on console. I should only use console.log()
to the value that I want to print out.
4) Write a function arrayOfRgbColors which return any number of RGB colors in an array.
function generateRgbColors() {
let rgbNum = [];
for (let i = 0; i < 3; i++) {
rgbNum[i] = Math.floor(Math.random() * 256);
}
return `rgb(${rgbNum.toString()})`;
}
function arrayOfRgbColors() {
let number = prompt('How many colors do you want?', 'Enter a number.'); //3
let generatedRgb= [];
for (let j = 0; j < number; j++) {
generatedRgb[j] = generateRgbColors();
}
console.log(generatedRgb);
}
arrayOfRgbColors(); //(3) ['rgb(37,140,238)', 'rgb(36,20,235)', 'rgb(211,0,95)']
The Math.random()
randomly returns a number between 0(inclusive) and 1(exclusive), so I have to multiply 256(which is 255+1) to get numbers from 0 to 255.
5) Write a function convertHexaToRgb which converts hexa color to rgb and it returns an rgb color.
I got the idea of converting from this article.
function convertHexaToRgb(hexa) {
let hexaNum = [];
for (let i = 0; i < 6; i++) {
switch (hexa.charAt(i)) {
case 'a': case 'A':
hexaNum[i] = 10;
break;
case 'b': case 'B':
hexaNum[i] = 11;
break;
case 'c': case 'C':
hexaNum[i] = 12;
break;
case 'd': case 'D':
hexaNum[i] = 13;
break;
case 'e': case 'E':
hexaNum[i] = 14;
break;
case 'f': case 'F':
hexaNum[i] = 15;
break;
default:
hexaNum[i] = hexa.charAt(i);
}
}
let red = hexaNum[0] * 16 + hexaNum[1];
let green = hexaNum[2] * 16 + hexaNum[3];
let blue = hexaNum[4] * 16 + hexaNum[5];
console.log(`rgb(${red},${green},${blue})`);
}
convertHexaToRgb('ffffff'); //rgb(255,255,255)
convertHexaToRgb('39ef96'); //rgb(57,239,150)
However, I found out that if I pass ‘000000’ as an argument, the function would return rgb(00,00,00), not rbg(0,0,0). This was because of the default
part on the upper code. If the character in a string wasn’t an alphabet between a to f, it would directly be assigned to an array as a string. So, I changed the type of the value using plus sign(+)
to change string into a number.
default:
hexaNum[i] = +(hexa.charAt(i));
6) Write a function convertRgbToHexa which converts rgb to hexa color and it returns an hexa color.
I got the idea of converting from this article(same article to above quiz).
function convertRgbToHexa(num1, num2, num3) {
let red1 = Math.floor(num1 / 16);
let red2 = ((num1 / 16) - Math.floor(num1 / 16)) * 16;
let green1 = Math.floor(num2 / 16);
let green2 = ((num2 / 16) - Math.floor(num2 / 16)) * 16;
let blue1 = Math.floor(num1 / 16);
let blue2 = ((num1 / 16) - Math.floor(num1 / 16)) * 16;
const hexa = [red1, red2, green1, green2, blue1, blue2];
const hexaColor = [];
for (let i = 0; i < 6; i++) {
switch (hexa[i]) {
case 10:
hexaColor[i] = 'a';
break;
case 11:
hexaColor[i] = 'b';
break;
case 12:
hexaColor[i] = 'c';
break;
case 13:
hexaColor[i] = 'd';
break;
case 14:
hexaColor[i] = 'e';
break;
case 15:
hexaColor[i] = 'f';
break;
default:
hexaColor[i] = hexa[i];
}
}
console.log(`#${hexaColor.join('')}`);
}
convertRgbToHexa(160, 186, 189); //#a0baa0
I wonder if there is a way that I can use parameters as a variable, because it would make the code a lot shorter at the first part(red1
, red2
, green1
, … the way it’s done is all same). I’ll come back for this later.
I came back from Day 8. I learned a new math method called Math.trunc()
, which just deletes the decimal numbers. I shortened the code like below.
function convertRgbToHexa(num1, num2, num3) {
let red1 = Math.trunc(num1 / 16);
let red2 = ((num1 / 16) - red1) * 16;
let green1 = Math.trunc(num2 / 16);
let green2 = ((num2 / 16) - green1) * 16;
let blue1 = Math.trunc(num1 / 16);
let blue2 = ((num1 / 16) - blue1) * 16;
const hexa = [red1, red2, green1, green2, blue1, blue2];
const hexaColor = [];
for (let i = 0; i < 6; i++) {
switch (hexa[i]) {
case 10:
hexaColor[i] = 'a';
break;
case 11:
hexaColor[i] = 'b';
break;
case 12:
hexaColor[i] = 'c';
break;
case 13:
hexaColor[i] = 'd';
break;
case 14:
hexaColor[i] = 'e';
break;
case 15:
hexaColor[i] = 'f';
break;
default:
hexaColor[i] = hexa[i];
}
}
console.log(`#${hexaColor.join('')}`);
}
convertRgbToHexa(160, 186, 189); //#a0baa0
7) Write a function generateColors which can generate any number of hexa or rgb colors.
console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b']
console.log(generateColors('hexa', 1)) // '#b334ef'
console.log(generateColors('rgb', 3)) // ['rgb(5, 55, 175)', 'rgb(50, 105, 100)', 'rgb(15, 26, 80)']
console.log(generateColors('rgb', 1)) // 'rgb(33,79, 176)'
function generateColors(type, number) {
if (type == 'hexa') {
generateHexaArray(number);
} else {
generateRgbArray(number);
}
}
function generateHexaColor() {
const hexa = 'abcdef0123456789';
const randHexa = [];
for (let i = 0; i < 6; i++) {
randHexa[i] = hexa.charAt(Math.floor(Math.random() * 16));
}
return `#${randHexa.join('')}`;
}
function generateHexaArray(number) {
const hexaColors = [];
for (let j = 0; j < number; j++) {
hexaColors[j] = generateHexaColor();
}
console.log(hexaColors);
}
function generateRgbColor() {
let rgbNum = [];
for (let i = 0; i < 3; i++) {
rgbNum[i] = Math.floor(Math.random() * 256);
}
return `rgb(${rgbNum.toString()})`;
}
function generateRgbArray(number) {
let generatedRgb= [];
for (let j = 0; j < number; j++) {
generatedRgb[j] = generateRgbColor();
}
console.log(generatedRgb);
}
generateColors('hexa', 3);
//(3) ['#39c5e9', '#08064c', '#21a9de']
generateColors('rgb', 2);
//(2) ['rgb(20,71,11)', 'rgb(185,178,15)']
At first, at the main function(one at the top) I just put generateHexaArray()
but there was an error that says ‘number
is not defined’. So to link the parameter of number into each separated function, I put a parameter of number
to use the argument value.
8) Call your function shuffleArray, it takes an array as a parameter and it returns a shuffled array
I wanted the function to pick one random element from the array, push it to a new array, remove the picked element from the original array, and then to pick another element from the remaining elements. My first approach was like below, using Math.random()
and splice()
, but it didn’t work out like I thought.
- First approach:
function shuffleArray(arr) {
const newArr = [];
for (let i = 0; i < arr.length; i++) {
newArr[i] = arr[Math.floor(Math.random() * arr.length)];
arr.splice(arr.indexOf(newArr[i]), 1);
console.log(arr);
}
console.log(newArr);
}
shuffleArray([1, 2, 3, 4, 5]);
Similar to picking a random character from a string, I should multiply the original length to
Math.random()
when picking a random element from an array. I don’t have to memorize it, but just remember to check the range before multiplying!
- Second approach:
function shuffleArray(arr) {
const newArr = [];
const length = arr.length;
for (let i = 0; i < length; i++) {
let currentLength = arr.length;
newArr[i] = arr[Math.floor(Math.random() * currentLength)];
arr.splice(arr.indexOf(Math.floor(Math.random() * currentLength)), 1);
currentLength--;
}
console.log(newArr);
}
shuffleArray([1, 2, 3, 4, 5]);
I spent a lot of time wondering why it wouldn’t work. After solving it, I think it was wrong because the Math.random()
worked separately over two lines. Those two numbers wouldn’t be the same because they’re executed separately. So, to make sure those two random numbers are the same, I changed the second Math.random()
to indexOf()
at my final approach, where it worked out.
Before that, I tried to declare random
in the for loop
like below:
let random = Math.floor(Math.random() * currentLength);
It didn’t work because the Math.random()
was only executed once, and the number would just be set and wouldn’t change through the loop.
- Final approach(answer):
function shuffleArray(arr) {
const newArr = [];
//setting a constant of length, to set the number of times that the loop is executed
const length = arr.length;
for (let i = 0; i < length; i++) {
//set another variable of length, but this one decrements over each loop
let currentLength = arr.length;
newArr[i] = arr[Math.floor(Math.random() * currentLength)];
//after the splice the length of an array would be decremented by 1
arr.splice(arr.indexOf(newArr[i]), 1);
currentLength--;
}
console.log(newArr);
}
shuffleArray([1, 2, 3, 4, 5]); //(5) [1, 3, 4, 2, 5]
shuffleArray([60, 5, 41, -80, 9, 60]); //(6) [-80, 60, 5, 60, 9, 41]
I searched over stackflow for further idea and found this site, where I could find some ideas to shorten my code.
-
I can push the returned value of
splice()
right into the new array. splice() returns the array of deleted elements. -
I can use
while
condition. The length of an array itself could work as condition, cause all numbers except 0 are truthy values. So if I decrement the length of an array each time, thepush
would be executed until there’s no element left in the array.
function shuffleArray(arr) {
const newArr = [];
let n = arr.length;
let i;
while (n) {
//set the random number, decrement the length over each loop
i = Math.floor(Math.random() * n--);
//push the first element(the picked element) of the returned array from splice
newArr.push(arr.splice(i, 1)[0]);
}
console.log(newArr);
}
shuffleArray([1, 2, 3, 4, 5]); //(5) [3, 4, 2, 5, 1]
- Further insight: I don’t have to set another variable if I shuffle it inside the original array argument. It would save a lot of time and space.
function shuffleArray(arr) {
let n = arr.length;
let i;
let t;
while (n) {
i = Math.floor(Math.random() * n--);
//picked element would move to the last place
//`t` would be a temporary storage for swapping
t = arr[n];
arr[n] = arr[i];
arr[i] = t;
}
console.log(arr);
}
shuffleArray([1, 2, 3, 4, 5]); //(5) [3, 2, 5, 1, 4]
9) Call your function factorial, it takes a whole number as a parameter and it return a factorial of the number.
The formula for calculating factorial is: n! = n * (n-1)!
. So to get the factorial, I would have to repeatedly multiply the decremented number until it reaches 1.
function factorial(num) {
let i = 1;
let numFact = 1;
while (i <= num) {
numFact*= i;
i++;
}
console.log(numFact);
}
factorial(4); //24
10) Call your function isEmpty, it takes a parameter and it checks if it is empty or not.
function isEmpty(parm) {
if (parm === undefined) {
console.log('The parameter is empty!');
} else {
console.log('The parameter is not empty.');
}
}
isEmpty(); //The parameter is empty!
isEmpty([1, 2, 3]); //The parameter is not empty.
isEmpty([]); //The parameter is not empty.
11) Call your function sum, it takes any number of arguments and it returns the sum.
function sum() {
let addAll = 0;
for (let i = 0; i < arguments.length; i++) {
addAll += arguments[i];
}
console.log(addAll);
}
sum(5, 10, 8, -17, 6); //12
Use
arguments
object to set a function with unlimited numbers of parameters!
12) Write a function called sumOfArrayItems, it takes an array parameter and return the sum of all the items. Check if all the array items are number types. If not, return a reasonable feedback.
function sumOfArrayItems(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] != 'number') {
return 'There is an element which is not a number.';
}
sum += arr[i];
}
return sum;
}
console.log(sumOfArrayItems([1, 5, -3, 9])); //12
console.log(sumOfArrayItems([6, 40, 'apple', -7])); //''There is an element which is not a number.'
To check if all the array items are number types, I used if
. At first I set the condition as typeof arr[i] != number
, but it had an error saying ‘number’ is not defined. The returned value of typeof
is a string, so I have to put single quotes, double quotes, or back-ticks to the type.
I also used an if else
conditional at first, but it didn’t work. I wanted the function to stop being executed the moment it detects an element which is not a number. There wasn’t a case of else
on that. So I deleted else
, and I used return
to terminate the code. I thought that the actual execution or calculation has to be done at last, after checking whether the condition is met, so I put the conditional at the beginning of the code. Again, chunking and separating the work is important.
13) Write a function called average, it takes an array parameter and returns the average of the items. Check if all the array items are number types. If not, return a reasonable feedback.
function average(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] != 'number') {
return 'There is an element which is not a number.';
}
sum += arr[i];
}
let average = sum / arr.length;
return average;
}
console.log(average([5, 14, 6, 15, 20])); //12
console.log(average([1, 5, 7, 'a', 3])); //There is an element which is not a number.
14) Write a function called modifyArray takes array as parameter and modifies the fifth item of the array and return the array. If the array length is less than five it return ‘item not found’.
console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']);
//['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']
function modifyArray(arr) {
if (arr.length < 5) {
console.log('Not Found');
} else {
arr.splice(4, 1, arr[4].toUpperCase());
console.log(arr);
}
}
modifyArray(['Apple', 'Banana', 'Orange', 'Melon', 'Blueberry', 'Mango']);
//(6) ['Apple', 'Banana', 'Orange', 'Melon', 'BLUEBERRY', 'Mango']
modifyArray(['Apple', 'Banana', 'Orange', 'Melon']); //Not Found
15) Write a function called isPrime, which checks if a number is prime number.
A prime number is a natural number greater than 1, which should only be divisible by exactly two numbers: 1 and itself.
function isPrime(num) {
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return `${num} is not a prime number.`;
} else {
return `${num} is a prime number.`;
}
}
}
console.log(isPrime(11)); // 11 is a prime number.
console.log(isPrime(20)); // 20 is not a prime number.
The number dividing the parameter(i
) should be between 2 and the parameter(num
, exclusive), because any number can be divided by 1. The purpose of the function is to check if any number(that is not 1 and itself) can divide the input number.
16) Write a function which checks if all items are unique in the array.
function uniqueArray(arr) {
for (let i = 0; i < arr.length; i++) {
if (arr.includes(arr[i], i + 1) == true) {
return 'There are same items in the array.';
} else {
return 'All items in the array are unique.';
}
}
}
console.log(uniqueArray([1, 5, 4, -7, 'a']));
//All items in the array are unique.
console.log(uniqueArray([5, 'n', 8, 5, 3]));
//There are same items in the array.
includes()
can take a second parameter offromIndex
, which sets the position to start searching the element.
Reading the document, I thought I could use it to detect whether the same element exists in the array. includes()
returns the boolean value.
- Another approach using Set:
I haven’t learned this object yet, but I’ve met this one at earlier exercise. Here’s a link of MDN document. Using Set
object, I can store unique values of any types. I’ll check if all items in the array are unique, by checking if the array is the same as Set(array).
function uniqueArray(arr) {
const unique = [...new Set(arr)];
if (arr.length === unique.length) {
return 'All items in the array are unique.';
} else {
return 'There are same items in the array.';
}
}
console.log(uniqueArray([1, 5, 4, -7, 'a']));
//All items in the array are unique.
console.log(uniqueArray([5, 'n', 8, 5, 3]));
//There are same items in the array.
At first, I set the condition as unique == arr
, but it didn’t work. It wouldn’t work because unique
is a different array from arr
. It just has same elements, and it doesn’t mean those two arrays could be same. I should have checked if the length of those two arrays are the same(in other words, to check whether there is any element removed), because if all the items are unique, no element would be removed at unique
.
17) Write a function which checks if all the items of the array are the same data type.
function checkDataType(arr) {
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] != typeof arr[i+1]) {
return 'Different data type detected.';
} else {
return 'All same data types.';
}
}
}
console.log(checkDataType([0, 85, -9, 4]));
//All same data types.
console.log(checkDataType([5, 'word', 1, -8]));
//Different data type detected.
I first tried to change all the elements of the array to the elements’ types, but I thought I could just use typeof
for that. I made the function compare itself to the next element. If there’s a difference, the function will be terminated and return ‘Different data type detected.’ Else if every element has same type to the elements beside it, I can tell that all the elements have the same data type.
18) JavaScript variable name does not support special characters or symbols except $ or _. Write a function isValidVariable which checks if a variable is valid or invalid variable.
function isValidVariable(str) {
let regex = /[^A-Za-z0-9]/
}
19) Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique.
function sevenRandomNumbers() {
let number = '0123456789'
let randNum = [];
let i = 10;
while (i > 3) {
randNum.unshift(number.charAt(Math.floor(Math.random() * i--)));
number = number.replace(randNum[0], '');
}
console.log(randNum);
}
sevenRandomNumbers(); //(7) ['8', '9', '7', '4', '1', '5', '0']
To make all the numbers unique, I decided to remove the selected number from the number string. Using unshift
, the selected value would always come at first. I used it to assign the same(first) value that would be replaced.
- Mistakes I’ve been through
1) I used splice()
. The variable number
isn’t an array, it’s a string. So I changed it to replace()
. Replacing the selected value to ‘’ would have the same effect of removing the selected element from array. I used unshift
to assign the same(first) value that would be replaced. The selected value would always come at first.
2) I set the while condition as i >= 3
. There should be only 7 numbers at the returned array, so it should be i > 3
(from 4 to 10).
3) I just put number.replace(randNum[0], '')
. The returned array had same elements. I should assign the new replaced number
string to change the variable at the next loop.
Later, I found that since I set the variable number
to a string, the function returned an array of strings. To make the function return an array of numbers, I added +(Plus sign)
like below. It’s for casting(converting the data type), and to convert a string to an integer I can also use parseInt()
or Number()
.
function sevenRandomNumbers() {
let number = '0123456789'
let randNum = [];
let i = 10;
while (i > 3) {
randNum.unshift(+(number.charAt(Math.floor(Math.random() * i--))));
number = number.replace(randNum[0], '');
}
for (let element of randNum) {
element = Number(element);
}
console.log(randNum);
}
sevenRandomNumbers(); //(7) [8, 6, 2, 1, 4, 7, 9]
20) Write a function called reverseCountries, it takes countries array, and first it copies the array and returns the reverse of the original array.
function reverseCountries(arr) {
const copyCountries = [];
for (let i = 0; i < arr.length; i++) {
copyCountries.push(arr[i]);
}
console.log(copyCountries.reverse());
}
reverseCountries(['Canada', 'Kenya', 'Ethiopia']);
//(3) ['Ethiopia', 'Kenya', 'Canada']
If I don’t have to copy the countries array, I can just use unshift()
to make the reversed array.
function reverseCountries(arr) {
const copyCountries = [];
for (let i = 0; i < arr.length; i++) {
copyCountries.unshift(arr[i]);
}
console.log(copyCountries);
}
reverseCountries(['Canada', 'Kenya', 'Ethiopia']);
//(3) ['Ethiopia', 'Kenya', 'Canada']
Leave a comment