KEMBAR78
Corrected JavaScript Exercise | PDF | Letter Case | Function (Mathematics)
0% found this document useful (0 votes)
12 views55 pages

Corrected JavaScript Exercise

This document contains 9 programming exercises in JavaScript along with their solutions. The exercises cover basic concepts such as functions, arithmetic operators, and strings to more advanced topics like arrays and recursive functions. The goal is to practice various problems in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views55 pages

Corrected JavaScript Exercise

This document contains 9 programming exercises in JavaScript along with their solutions. The exercises cover basic concepts such as functions, arithmetic operators, and strings to more advanced topics like arrays and recursive functions. The goal is to practice various problems in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Corrected JavaScript Exercise - Part 1

April 14, 2020


programming
test

A here are corrected exercises in JavaScript, you will practice various


concepts of the JavaScript language. You will start with exercises
JavaScript from basic to more advanced exercises. The solution is provided for
each exercise. You must try to solve each problem by
yourself before checking the solution. If you have any questions
regarding each issue, we encourage you to post them on
notreforum.

Exercise 1:
Create a function that takes two numbers as arguments and returns
their sum.

Example:
addition(1, 2) ➞ 3

addition(-2, -4) ➞ -6

Corrected
Solution:
function addition(x, y) {
if(typeofx !== 'number' || typeofy !== 'number') {
Error: please enter two numbers!
}
return x + y;
}

Exercise 2:
Write a function that takes an integer number of minutes and converts it into
seconds.

Example:
minuteToSecond(4)➞ 240
180➞ 180

Corrected
Solution:
function minuteToSecond(minutes) {
return minutes * 60;
}

Exercise 3:
Create a function that takes a number as an argument, increments the number
+1 and return the result.

Example:
increment(1)➞ 2

increment(4)➞ 5

Corrected
Solution:
function increment(n) {
return++n;
}

Exercise 4:
Write a function that takes the base and height of a triangle and returns
The area of a triangle is: (base * height) / 2

Example:
getSurface(8, 2)➞ 8

getSurface(7, 3)➞ 10.5

Corrected
(base * height) / 2
Solution:
function getSurface(base, height) {
base * height / 2
}
Exercise 5:
Write a JavaScript program to reverse a string.

Example:
XnraelToYaW➞ XnraeLoTyaW

olleH➞ Hello

Corrected
Solution:
function strReverse(str) {
returnstr.split('').reverse().join('');
}

Exercise 6:
Write a JavaScript program to find the largest of three integers
given.

Example:
getMax(5, 9, 1) ➞ 9

getMax(2, 3, 10) ➞ 10

Corrected
Solution:
function getMax(a, b, c) {
max =0;
if(a > b){
max = a;
}
else{
max = b;
}
if(c > max){
max = c;
}
returnmax;
}
Exercise 7:
Create a function that takes an array and returns the first element. Note
the first element of an array always starts with index 0.

Example:
getFirst([1, 2, 3]) ➞ 1

getFirst([50, 60, 70]) ➞ 50

Corrected
Solution:
function getFirst(tab) {
returntab[0];
}

Exercise 8:
Write a JavaScript program to retrieve the URL of a website

// Write your code here

Corrected
Solution:
console.log(document.URL);
See also: How to retrieve the URL of the current page with JavaScript

Exercise 9:
Write a JavaScript program to return the remainder of two numbers. It
there is only one operator in JavaScript capable of providing the remainder of a
division. Two numbers are passed as parameters. The first
parameter divided by the second parameter.

Example:
resteDiv(1, 3) ➞ 1

resteDiv(2, 4) ➞ 2

resteDiv(3, 3) ➞ 0

Corrected
Solution:
function remainderDiv(a, b) {
return a % b;
}

Exercise 1:
Correct the following code (Syntax error) to calculate the square.
Example:
square(2)➞ 4

carre(4) ➞ 16
Corrected
Solution:
function square(b) {
return b * b;
}

Exercise 2: < 100


With two numbers, return TRUE if the sum of the two numbers is
less than 100. Otherwise, return FALSE.
Example:
check(5, 20)➞ true
5 + 20 = 25

check(60, 55)➞ false


60 + 55 = 115
Corrected
Solution:
functioncheck(a, b) {
return a + b < 100;
}

Exercise 3:
Write a function that converts hours into seconds. Note that there are
60 seconds in a minute and 60 minutes in an hour.
Example:
second(1)➞ 3600

secondHour(5)➞ 18000

Corrected
Solution:
function timeInSeconds(hour) {
return hour * 3600;
}

Exercise 4:
Create a function that takes a number and returns TRUE if it is
less than or equal to zero, otherwise return FALSE.

Example:
checkNbr(1)➞ false

checkNbr(-1)➞ true

checkNbr(0)➞ true
Corrected
Solution:
function checkNbr(n) {
returnn <= 0;
}

Exercise 5:
Create a function that returns TRUE when nbr1 is equal to nbr2; otherwise
return FALSE.
Example:
isEqual(3, 6)➞ false

isEqual(1, '1')➞ false

isEqual(1, 1) ➞ true
Corrected
Solution:
function isEqual(nbr1, nbr2) {
returnnbr1 === nbr2
}

Exercise 6:
Create a function that returns TRUE if an integer is divisible by 5,
otherwise return FALSE.
Example:
isDivisible(5)➞ true

isDivisible(10)➞ true

isDivisible(6)➞ false
Corrected
Solution:
function isDivisible(n) {
returnn %5===0;
}

Exercise 7:
Write a function that takes two integers (hours, minutes) and them
convert to seconds.
Example:
hmTos(1, 10)➞ 4200

hmTos(0, 59)➞ 3540

hmTos(0, 0)➞ 0
Corrected
Solution:
function hmTos(hour, minute) {
return(hour*3600)+(minute*60);
}
Exercise 8:
Write a function to reverse an array. Attention: Do not use the
integrated method reverse();
Example:
reverseTab([1, 2, 3]) ➞ [3, 2, 1]

reverseTab([1, 1, 2, 2, 3]) ➞ [3, 2, 2, 1, 1]


Corrected
Solution:
function reverseTab(tab) {
letters = [];
for(let i = tab.length-1; i > -1; i--) {
res.push(tab[i]);
}
returnres;
}

Exercise 9:
Create a function that takes an array and returns the last element of it.
tableau.
Example:
getLastElem([1, 2, 3, 4])➞ 4

getLastElem(['Alex', 'Bob', 'Emily'])➞ Emily


Corrected
Solution:
function getLastElem(tab) {
returntab[tab.length-1]
}

Exercise 1:
Create a function that checks the equality of two parameters a and b. The value and the type of
parameters must be tested in order to have equality. The function must return TRUE if the
parameters are equal and FALSE if they are different.
Example:
checkEq(5, 5)➞ true
// number = number: their type and their value are equal

checkEq(5, 0)➞ false


// number = number: their types are equal and their values are different

checkEq(5, false)➞ false


// number <> boolean: their type is different

checkEq(5, '5')➞ false


number <> string: their type is different

Corrected
Solution:
Transitional manager, should one be...
Pause

Unmute

Loaded: 41.52%

Remaining Time -4:07

Fullscreen

Transition manager, Should one be independent?

function checkEq(a, b) {

returna === b;

}
See also:Difference between == and === in JavaScript

Exercise 2:
Create a function that returns TRUE if a string is empty and FALSE otherwise.

Example:

isEmpty("1")➞ false

isEmpty("WayToLearnX")➞ false
isEmpty(" ")➞ false

isEmpty("") ➞ true

Corrected
Solution:

function isEmpty(str) {

returnstr.length==0;

Exercise 3: Concatenate two strings into a single string


With two strings, str1 and str2, return a single string in the format "str1 | str2".

Example:

TrueFalse➞ True | False

OnOff➞ On | Off

AB➞ A | B

Corrected
Solution:

function concatStr(str1, str2) {

return `${str1} | ${str2}`;

Exercise 4:
Create a function that takes a name and returns a welcome message in the form of a
chain. Do not use a normal function but use aarrow function
Example:

Thomas➞ Hello Thomas, Welcome to WayToLearnX!

Alex➞ Hello Alex, Welcome to WayToLearnX!

Emily➞ Hello Emily, Welcome to WayToLearnX!

Corrected
Solution:

Hello {name}, Welcome to WayToLearnX!


See also:Arrow functions in Javascript

Exercise 5:
Write a function that returns the length of a string. Use a recursive function.

Example:

size("alex") ➞ 5

size("x")➞ 1

size("")➞ 0

Corrected
Solution:

function size(str, n = 0) {

if(str[n] === undefined) {

returnn
}

returnsize(str, n +1)

Exercise 6:
Create a function that takes two strings str1 and str2 as arguments and returns TRUE if
the total number of characters in the first string is equal to the total number of characters
in the second chain otherwise return FALSE.

Example:

compareSize("AA", "BB")➞ true

compareSize("123", "1")➞ false

compareSize("Ali", "Bob")➞ true

Corrected
Solution:

function compareSize(str1, str2) {

returnstr1.length=== str2.length;

Exercise 7:
Create a function that takes the height and width and finds the perimeter of a rectangle.

Example:
getPerimeter(2, 6) ➞ 16

getPerimeter(3, 10) ➞ 26

getPerimeter(1, 5)➞ 12

Corrected
The formula to calculate the perimeter of a rectangle is (height + width) * 2
Solution:

function getPerimeter(height, width) {

return(height + width)*2;

Exercise 8: The Farmer's Problem


In this challenge, a farmer asks you to tell him how many legs can be counted.
among all its animals. There are three species:

. chickens = 2 legs

. cows = 4 legs

. horses = 4 legs

The farmer counted his animals and gives you a subtotal for each species. You
You must implement a function that returns the total number of legs of all the animals.

The order of animals passed to the function isnbrsPattes(chickens, cows, horses).

Example:
nbrsPattes(1, 4, 2) ➞ 26

nbrsPattes(2, 2, 2)➞ 20

nbrsPattes(2, 0, 3) ➞ 16

Don't forget that the farmer wants to know the total number of legs and not the number.
total of animals.

Corrected
Solution:

function numberOfLegs(chickens, cows, horses) {

return chickens * 2 + (cows + horses) * 4;

Exercise 9: Odd or Even Number


Create a function that takes a number as an argument and returns "even" for the
even numbers and 'odd' for odd numbers.

Example:
check(2)➞ pair

check(7)➞ impair

check(22)➞ pair

Corrected
Solution:

function check(n) {

return n % 2 ? 'odd' : 'even';

Exercise 1:
Create a function to concatenate two integer arrays.

Example:
concatener([1, 2], [3, 4]) ➞ [1, 2, 3, 4]

concatener([9, 8], [1, 5, 6, 7]) ➞ [9, 8, 1, 5, 6, 7]

concatener([1, 1, 1], [2, 2, 2]) ➞ [1, 1, 1, 2, 2, 2]

Corrected
The three dots (…) represent the "Spread" operator in ES6 which allows for a
expression of being broadened.
Solution:
function concatenator(tab1, tab2) {
return [...tab1, ...tab2]
}

Exercise 2:
Create a function that finds the index of a given element. If the element does not exist,
return -1.

Example:
find([2, 7, 1], 7) ➞ 1

find([6, 9, 5], 6) ➞ 0

find([6, 7, 8], 9) ➞ -1

Corrected
Solution:
function find(tab, val) {
for(i = 0; i < tab.length; i++){
if(tab[i] == val) return i;
}
return-1;
}

Exercise 3:
Write a function to check if an array contains a particular number.

Example:
nbrExist([6, 7, 8], 7)➞ true

numberExists([1, 2, 3], 5)➞ false

nbrExist([], 0)➞ false

Corrected
Solution:
function numberExist(tab, val) {
for(i = 0; i < tab.length; i++){
if(tab[i] === val) {
return true;
}
}
return false;
}
How to become a transition manager...
Pause
Unmute
Loaded: 25.60%

Remaining Time -6:15


Fullscreen

How to become a transition manager

Exercise 4:
Create a function that takes a string (a random name). If the last character of the name is
if it is an 's', return TRUE, otherwise return FALSE.

Example:

checkS("Thomas")➞ true

checkS("Ali")➞ false

checkS("Alex")➞ false

checkS("Alvis")➞ true

Corrected
Solution:
function checkS(str) {
returnstr[str.length-1]==="s";
}

Exercise 5:
Create a function that returns TRUE if a string contains spaces. Otherwise return
FALSE.

Example:

containSpaces("Thomas")➞ false

Hello World!➞ true


➞ true

➞ false

Corrected
Solution:
function contain Spaces(str) {
returnstr.includes(' ')
}

Exercise 6:
Create a function that takes an object as an argument and returns a string that represents
a person. The attributes of the person must be extracted from the three properties of the object:

. name

. age

. address

The sentence must be in the following format: X is Y years old. He lives in Z. (where X is the name of the
person, Y is the age and Z is the address.

Example:

The given text is incomplete or does not contain translatable content.

Thomas

25

Paris

})

➞ Thomas is 25 years old. He lives in Paris.

formatPrs({

Emily
22

Nantes

})

➞ Emily is 22 years old. She lives in Nantes.

Corrected
Solution:
function formatPrs(person) {
{person.name} is {person.age} years old. He lives in {person.address}.
}

Exercise 7:
Create a function that takes a string representing the mood and returns a sentence.
format following: "Today, I feel {feeling}". However, if no argument is
Today, I feel neutral.

Example:

happy➞ Today, I feel happy

sad➞ Today, I feel sad

myFeeling()➞ Today, I feel neutral

Corrected
Solution:
function myFeeling(feeling) {
Today, I feel ${feeling || "neutral"}
}

Exercise 8:
Create a function that returns the number of arguments it was called with.

Example:
nbrArgs()➞ 0

nbrArgs({})➞ 1

nbrArgs(A)➞ 1

nbrArgs("A", "B")➞ 2

Corrected
Solution:
functionnbrArgs() {
returnarguments.length;
}

Exercise 9:
Create a function that takes a word and determines if it is plural or singular. A plural word
is the one that ends with "s". If it is plural return TRUE otherwise FALSE.

Example:

children➞ true

girls➞ true

girl➞ false

child➞ false

Corrected
Solution:
functioncheck(str) {
returnstr[str.length-1]=='s';
}

Exercise 1:
Write a function that takes an integer and:

. If the number is a multiple of 3, return 'Hello'.

. If the number is a multiple of 5, return 'World'.

. If the number is a multiple of 3 and 5, return 'Hello World'.

Example:

checkNbr(3)➞ Hello

checkNbr(5)➞ World

checkNbr(15)➞ Hello World

Corrected
Solution:
function checkNbr(n) {
return n % 15 === 0 ? 'Hello World' : n % 3 === 0 ? 'Hello' : 'World';

Exercise 2:
Write the regular expression that reveals the hidden message. You need to remove all the
names to reveal the message. Use the character class \D in your expression.

Corrected
Used to find the non-numeric character. Match is performed.
global.
Solution:
varpatt = /\D */g;
Exercise 3:
Create a function that takes an array with numbers and returns an array with the
elements multiplied by two.

Example:
tabX2([1, 2, 3]) ➞ [ 2, 4, 6 ]

tabX2([5, 10, 20]) ➞ [ 10, 20, 40 ]

tabX2([100, 200, 300]) ➞ [ 200, 400, 600 ]

Corrected
Solution:
functiontabX2(tab) {
returntab.map(i => i * 2)
}

Exercise 4:
Create a function that takes three numbers as arguments and returns TRUE if it is a
triangle, else returns FALSE.

Example:

isTriangle(2, 3, 4)➞ true

isTriangle(2, 4, 5)➞ true

isTriangle(8, 2, 1) ➞ false

Note that a, b, and c are the lengths of the sides of the triangle.

Corrected
Determining if the lengths of the three sides can form a triangle is easier. All that
All you have to do is use the inequality theorem, which states that the sum of the lengths
The sum of the lengths of any two sides of a triangle is always greater than the length of the third side. If this is true for the
three combinations, you will have a triangle.
The formula:
a+b>c
a+c>b
b+c>a

Solution:
function isTriangle(a, b, c) {
return a + b > c && b + c > a && c + a > b
}

Exercise 5:
Create a function that returns the ASCII value of the given character.

Example:

charToAscii("A")➞ 65

charToAscii("a") ➞ 97

charToAscii("+")➞ 43

Corrected
The method charCodeAt() returns an integer between 0 and 65535 representing the unit of
UTF-16 code at the given index.
Solution:
function charToAscii(c) {
returnc.charCodeAt(0);
}

Exercise 6:
With a fraction in string form, indicate whether it is greater than 1 or not.
when it is evaluated.

Example:

FracSup1("2/2")➞ false

Fraction Supremum 1 of 8 divided by 2➞ true

FracSup1("1/2")➞ false
Corrected
eval() is a global function in JavaScript that evaluates a specified string as code.
JavaScript and it executes.
Solution:
functionFracSup1(f) {
returneval(f)>1;
}

Exercise 7:
Create a function that takes an array and returns the sum of all the numbers in the array.

Example:

sum([1, 1, 1]) ➞ 3

sum([1, 2, 3])➞ 6

sum([-2, 2, 1]) ➞ 1

Corrected
Solution:
function sum(tab) {
lets =0
for(let i = 0; i < tab.length; i++) {
s += tab[i]
}
returns
}

Exercise 8:
Create a function that takes an array of words and transforms it into an array of lengths.
each word.

Example:

countStr(["A", "B", "C"])➞ [1, 1, 1]


countStr(["Welcome", "To", "WayToLearnX"]) ➞ [7, 2, 11]

countStr(["Bob", "Ali", "Thomas"])➞ [3, 3, 6]

Corrected
Solution:
function countStr(tab) {
returntab.map(str => str.length);
}

Exercise 9:
Create a function that returns the number of syllables in a string.

Example:

nbrOfSyllables("SOSOSOSO")➞ 4

number of syllables➞ 5

nbrOfSyllables("RIRIRIRIRIRIRIRIRIRI")➞ 10

Solution:
function numberOfSyllables(str) {
returnstr.length/2;
}

Exercise 1:
Create a function that takes a string and returns TRUE or FALSE, depending on whether the characters
are in order or not.

Example:

checkOrder("abc")➞ true

The input provided does not contain translatable text.➞ false

checkOrder("123")➞ true

checkOrder("aabbcc")➞ true

Corrected
Solution:

function checkOrder(str) {

returnstr === str.split('').sort().join('')

Exercise 2:
Create a function that adds a substring to the end of each string in the array.

Example:

addEnd(["accept", "achet", "adapt"], "able") ➞ ["acceptable", "achetable", "adaptable"]

addEnd(["aim", "act", "ard"], "ant") ➞ ["aimant", "actant", "ardant"]

Corrected
Solution:

function addEnd(array, end) {


returntableau.map(word => word + end);

Exercise 3:
Create a function that checks if the argument is an integer or a string. Returns 'int' if it
it is an integer and "string" if it is a string.

Example:

checkIntOrStr("WayToLearnX")➞ string

checkIntOrStr(1)➞ int

checkIntOrStr("250")➞ string

Corrected
Solution:

function checkIntOrStr(x) {

if(typeofx ==="number") {

return "int";

}else if(typeofx ==="string") {

return"string";

Exercise 4:
Create a function that takes a sentence and returns the number of words.

Example:
Welcome to WayToLearnX➞ 3

count("Hello World")➞ 2

I am going to my school➞ 6

Corrected

Exercise 5:
Create a recursive function that returns the total of all odd numbers up to
n (inclusive). n will be given as an odd number.

Example:

sommeImpair(3) ➞ 4

1+3=4

sommeImpair(7) ➞ 16

sommeImpair(59) ➞ 900

Corrected
Solution:

function sommaImpair(n) {

if(n === 1)return 1

return +sumOdd(n - 2)

Exercise 6:
Create a function that returns TRUE if the string passed as a parameter contains only
uppercase or lowercase letters.
Example:

isSameCase("WayToLearnX")➞ false

isSameCase("waytolearnx")➞ true

isSameCase("WAYTOLEARNX")➞ true

Corrected
Solution:

function isSameCase(str) {

returnstr.toUpperCase() === str || str.toLowerCase() === str;

Exercise 7:
Create a function to multiply all the values of an array by the length of the array.
given.

Example:

mulByLen([1, 1, 1])➞ [ 3, 3, 3 ]

mulByLen([1, 2, 3])➞ [ 3, 6, 9 ]

mulByLen([0, 0, 0, 0, 2])➞ [ 0, 0, 0, 0, 10 ]

Corrected
Solution:

function mulByLen(tab) {
returntab.map(x => x * tab.length);

Exercise 8:
Create a function to remove all null values from an array.

Example:

deleteNull(["Alex", null, "Emily", "Bob"]) ➞ ["Alex", "Emily", "Bob"]

deleteNull([0, 1, null, 2, null, 3]) ➞ [0, 1, 2, 3]

deleteNull([null, null, null]) ➞ []

Corrected
Solution:

function deleteNull(tab) {

returntab.filter(i => i !== null)

Exercise 9:
A leap year has an extra day added to February to be synchronized with the year.
leap year. A leap year occurs at a regular frequency, determined by the
rule below:

A year must be divisible by 400 or divisible by 4 and not by 100.

You need to implement a function that returns TRUE if it is a leap year, or


FALSE if it is not the case.

Example:

leap year (2020)➞ true

Divided by 4 and not by 100.


leap year➞ false

Divided by 4, but also divided by 100.

leap year(2000)➞ true

Divided by 400.

Corrected
Solution:

function leapYear(year) {

return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0;

Exercise 1:
Create a function that finds all the even numbers from 1 to the given number.

Example:

evenNumber(6)➞ [2, 4, 6]

pairNumber(4)➞ [2, 4]

evenNumber(2)➞ [2]

Corrected
Solution:

function evenNumber(n) {
letpaire = [];

for(let i = 1; i <= n; i++) {

if(i % 2 === 0) {

pair.push(i);

return pair;

Exercise 2:
Write a function that returns TRUE if all the characters in a string are identical.
otherwise returns FALSE.

Example:

isSame("bbbbbb")➞ true

isSame("abababab")➞ false

isSame("111111")➞ true

Corrected
Solution:

function isSame(str) {

return new Set([...str]).size === 1;

Exercise 3:
You have an array of numbers, transform this array into a mirror.

Example:
[1, 2, 3]➞ [1, 2, 3, 2, 1]

mirror([9, 8, 7])➞ [9, 8, 7, 8, 9]

mirror([10, 20])➞ [ 10, 20, 10 ]

Corrected
Solution:

function mirror(tab) {

return [...tab, ...tab.splice(0, tab.length-1).reverse()]

Exercise 4:
Write a recursive function that finds the sum of the first n natural numbers.

Example:

sum(3)➞ 6

1+2+3=6

sum(2)➞ 3

sum(10)➞ 55

Corrected
Solution:

function sum(n) {

if(n == 0) {
returnn;

returnn +sum(n -1);

Exercise 5:
Create a function to extract the category name from its URL.

Example:

The provided text is a code snippet and does not contain translatable content.➞ html

Invalid input for translation.➞ css

getCategory("https://waytolearnx.com/javascript/")➞ javascript

Corrected
Solution:

function getCategory(url) {

returnurl.split("/")[3]

Exercise 6:
Write a function that returns TRUE if an object is empty, otherwise returns FALSE.

Example:

isObjEmpty({ a: 1, b: 2 })➞ false

isObjEmpty({ a: 1 })➞ false


isObjEmpty({})➞ true

Corrected
Solution:

function isObjEmpty(obj) {

return!Object.keys(obj).length

Exercise 7:
Write a function that retrieves the last n elements of an array.

Example:

lastNitem([8, 1, 5, 2, 4, 9], 3) ➞ [2, 4, 9]

lastNitem([1, 2, 3], 1) ➞ [3]

lastNitem([1, 2, 3, 4], 10)➞ invalid

lastNitem([1, 2, 3, 4], 0) ➞ []

Corrected
Solution:

functionlastNitem(t, n) {

return n <= t.length ? t.slice(t.length - n, t.length) : 'invalid';

}
Exercise 8:
Write a function that removes all special characters from a string.

Example:

WalyTo8oLe rnX➞ WayToLearnX

ALe x➞ ALex

Hello➞ Hello

Corrected
Solution:

function removeSpecialChar(str) {

returnstr.replace(/[^a-z]/gi,'');

Exercise 9:
Write a function that returns TRUE if a number is a palindrome.

Example:

checkPalindrome(212)➞ true

checkPalindrome(123)➞ false

checkPalindrome(75257)➞ true

Solution:

function checkPalindrome(n) {
returnString(n).split('').reverse().join('')==String(n);
}

Exercise 1:
The Hamming distance is the number of characters that differ between two strings. Let's take
an example:

abcdde
abcdbe

Hamming distance = 1, where 'd' and 'b' are the only difference.

Create a function that calculates the Hamming distance between two strings.

Example:

distanceHamming("abcdde", "abcdbe") ➞ 1

distanceHamming("abefcd", "cdfgea") ➞ 6

distanceHamming("agresser", "adresser") ➞ 1

distanceHamming("attention", "intention") ➞ 2

Corrected
Solution:
#YouTube would have set up a new...
Replay

Unmute

Loaded: 100.00%

Remaining Time -0:00

Fullscreen

YouTube would have set up a new system preventing the use of the #AdBlock extension

function distanceHamming(str1, str2) {


return[...str1].filter((x, i)=>x != str2[i]).length

Exercise 2:
Create a function that takes an array of numbers and returns the minimum and the maximum
in an array [Min, Max].

Example:

getMinMax([8, 1, 9, 2, 6]) ➞ [1, 9]

getMinMax([22, 2]) ➞ 2, 22

getMinMax([5]) ➞ [5, 5]

Corrected
Solution:

function getMinMax(tab) {

return [Math.min(...tab), Math.max(...tab)];

Exercise 3:
Create a function that counts the number of uppercase letters in a string.

Example:

countMaj("abcdEFG") ➞ 3

countMaj("WayToLearnX")➞ 4

countMaj("abcdefghigklmnopkrstvuwxyz")➞ 0
Corrected
Solution:

function countMaj(str) {

returnstr.split(/[A-Z]/).length-1;

Exercise 4:
Create a function that counts the number of syllables in a word. Each syllable is separated
by a hyphen -.

Example:

numberOfSlab("spring-time")➞ 2

number of slabs➞ 3

numberOfSlab("ther-mo-meter") ➞ 4

Corrected
Solution:

function numberOfSlab(str) {

returnstr.split("-").length;

Exercise 5:
Implement a function that returns the given distance in kilometers converted to miles.
You must round the result to the fourth decimal place.

Example:

toMiles(5) ➞ 3.1069
toMiles(7)➞ 4.3496

toMiles(10) ➞ 6.2137

Corrected
Solution:

functiontoMiles(km) {

return parseFloat((km * 0.621371).toFixed(4))

Exercise 6:
Create a function that takes a number (from 1 to 12) and returns its month name.
correspondent in the form of a string. For example, if you are given 4 as input, your
the function should return April, because April is the 4th month.

Name Name of the month

1 January

2 February

3 Mars

4 April

5 Me

6 June

7 July

8 August

9 September

10 October

11 November

12 December
Example:

monthName(3)➞ Mars

nameOfMonth(12)➞ December

monthName(6)➞ June

Corrected
Solution:

function monthName(n) {

constmois ={

January

February

Mars

April

May

June

July

August

September

October

November

December

};

returnmois[n];

}
Exercise 7:
Create a function that returns 'Uppercase' if all the letters of a word are in
uppercase, " lowercase " if all the letters of a word are in lowercase and " Mix " if it
contains both uppercase and lowercase letters.

Example:

WAYTOLEARNX➞ Uppercase

caseOf("waytolearnx")➞ Minuscule

WayToLearnX➞ Mix

Corrected
Solution:

function caseOf(str) {

returnstr === str.toUpperCase()?'Uppercase':

str === str.toLowerCase() ? 'Lowercase' : 'Mix';

Exercise 8:
Time has a format: hours:minutes. The hours and minutes have two digits, like
07:00. Write the regular expression to find the time (hours:minutes) in the string.

Example:

The restaurant opens at 08:00 located on Boulevard du 200:200➞ 08:00

I had my lunch at 10:30.➞ 10:30


I am going to the cinema tomorrow at 6:00 PM.➞ 6:00 PM

Corrected
Solution:

varexpr =/\d{2}:\d{2}/

Exercise 9:
Write a function that takes an 8-bit binary number in the form of an array and
convert it to decimal.

Example:

binToDec([0, 0, 0, 1, 1, 1, 1, 1])➞ 31

binToDec([0, 0, 0, 0, 0, 0, 0, 1]) ➞ 1

binToDec([1, 0, 0, 0, 0, 0, 0, 0]) ➞ 128

Corrected
Solution:

function binToDec(tab) {

return parseInt(tab.join(""), 2);

Exercise 1:
A palindrome is a word that is written the same way after reversing it.
'ada' is a palindrome. Write a method that checks if a string is a palindrome.

Example:
isPalindrome("NON") ➞ true

isPalindrome("TOTO") ➞ false

SOS is a palindrome.➞ true

SELLES is not a palindrome.➞ true

Corrected
Solution:

function isPalindrome(str) {

return [...str].reverse().join('') == str

Exercise 2:
Write a function that takes two numbers and returns whether they should be added.
subtracted, multiplied, or divided to obtain 8. If none of the operations can yield 8,
return NULL.

Example:

operation(4, 4)➞ to add

10 divided by 2➞ subtract

operation(32, 4)➞ divide

operation(6, 6)➞ NULL


Corrected
Solution:

functionoperation(n1, n2) {

if(n1 + n2 === 8) {

return 'add';

else if(n1 * n2 === 8) {

return 'multiplier';

}else if(n1 - n2 === 8) {

subtract

}else if(n1 / n2 ===8) {

return'divider';

return null;

Exercise 3:
You have hired three salespeople and you pay them. Create a function that takes three
names (the hourly wage of each salesperson) and returns the difference between the
the highest paid and the lowest paid commercial

Example:

getDiff(200, 10, 90) ➞ 190

//200 - 10 = 190

getDiff(56, 29, 16) ➞ 40

getDiff(2, 10, 5) ➞ 8
Corrected
Solution:

function getDiff(c1, c2, c3) {

return Math.max(...arguments) - Math.min(...arguments)

Exercise 4:
You have an array of numbers, create a function that returns the same array but with
the index of each element in the array added to itself. This means you add 0
at index 0, add 1 to the number at index 1, add 2 to the number at index 2, etc...

Example:

addIndexeToElem([0, 0, 0, 0])➞ [0, 1, 2, 3]

addIndexeToElem([2, 1, 0, 1]) ➞ [2, 2, 2, 4]

addIndexeToElem([9, 8, 7, 6]) ➞ [9, 9, 9, 9]

Corrected
Solution:

function addIndexToElem(tab) {

returntab.map((val,i)=>val + i);

Exercise 5:
Create a function that takes a string and returns a string with spaces between all the
characters.

Example:

addSpace("waytolearnx")➞ way to learn x


addSpace("Hello BoB")➞ Hello Bob

Thank you➞ Thank you

Corrected
Solution:

function addSpace(str) {

return [...str].join(' ');

Exercise 6:
You have a table of drinks, each drink being an object with two properties: name and
price. Create a function that takes the array of drinks as an argument and returns the object.
drinks sorted by price in ascending order.

Suppose that the following array of beverage objects needs to be sorted:

boissons = [

lemon

mint

strawberry

The output of the sorted drinks object will be:

Example:

sortByPrice(drinks)➞ [

strawberry
mint

lemon

Corrected
Solution:

function sortByPrice(drinks) {

return drinks.sort((a, b) => a.price - b.price);

Exercise 7:
A uniform number is a positive number made up of the same digit.

Create a function that takes an integer and returns whether it is a uniform number or not.

Example:

isUniform(444)➞ true

isUniform(-444)➞ false

isUniform(0)➞ true

Corrected
Solution:

function isUniform(n) {

return new Set('' + n).size === 1

Exercise 8:
With two strings, create a function that returns the total number of unique characters from them.
concatenated chain.

Example:

eiont➞ 6

"attentionintention" 6 unique characters:

atenio

uniqueChr("plus", "tous")➞ 6

uniqueChr("bis", "lis")➞ 4

Corrected
Solution:

function uniqueChr(s1, s2) {

return new Set(s1 + s2).size;

Exercise 9:
Write a recursive function that finds the sum of an array.

Example:

somme([1, 2, 3]) ➞ 6

sum([1, 2])➞ 3

sum([])➞ 0

Corrected
Solution:

function some(tab) {

if(tab.length === 0)

return0;

else

returntab.pop() + sum(tab);

Exercise 1:
Create a function that accepts two parameters and, if both parameters are strings,
add them as if they were integers or if both parameters are integers,
concatenate them.

Example:

add(2, 3)➞ 5

add(2, 3) ➞ 23

add("2", 3)➞ null

Corrected
Solution:

functionadd(a, b) {

if(typeofa !==typeofb)

return null;

if(typeofa === 'string')


returnNumber(a) + Number(b);

return `${a}${b}`;

Exercise 2:
Create a function that returns the product of all the odd integers in an array.

Example:

prodImp([1, 2, 3, 4]) ➞ 3

prodImp([3, 6, 8, 5, 5, 7]) ➞ 525

prodImp([1, 0, 1, 0, 1, 0]) ➞ 1

Corrected
Solution:

function prodImp(tab) {

returntab.filter(i=>i %2!==0).reduce((a,b)=>a * b);

Exercise 3:
Create a function that repeats each character in a string n times.

Example:

alexalexalex➞ aaallleeexxx

waytolearnx➞ waytolearnx
bobbob➞ bboobb

Corrected
Solution:

function repeatChr(str, n) {

returnstr

.split('')

.map(c=>c.repeat(n))

.join('');

Exercise 4:
You have a list of random words, but your program does not accept the words.
starting with the uppercase letter 'Z'. Remove the unacceptable words and send it back
new table.

Example:

filterWords(["Bob", "Alex", "Zoello"]) ➞ ["Bob", "Alex"]

filterWords(["Lion", "Zebra", "Gazelle"]) ➞ Lion

filterWords(["Mercedes", "Bmw", "Audi"]) ➞ ["Mercedes", "Bmw", "Audi"]

Corrected
Solution:

function filterWords(tab) {

returntab.filter(str=>/^[^Z]/.test(str))

}
Exercise 5:
Write a function that takes an array of elements and returns only the integers.

Example:

getInt([1, 2, "3", "4", "5", 6]) ➞ [1, 2, 6]

getInt(["Vache", 20, "Cheval", 1, "Poule", 50]) ➞ [20, 1, 1]

getInt(["Str", false, 5.56, 6])➞ [6]

Corrected
Solution:

function getInt(tab) {

returntab.filter(Number.isInteger);

Exercise 6:
Create a function that converts two arrays of x and y coordinates into an array of
coordinates (x, y).

Example:

convert([0, 2, 5], [8, 6, 9]) ➞ [ [ 0, 8 ], [ 2, 6 ], [ 5, 9 ] ]

convert([2, 2], [4, 8]) ➞ [ [ 2, 4 ], [ 2, 8 ] ]

[1] converted to [2]➞ [[1, 2]]

Corrected
Solution:
functionconvert(tabX, tabY) {

returntabX.map((ix, iy)=>[ix, tabY[iy]])

Exercise 7:
Create a function that replaces all the vowels in a string with a specified character.

Example:

r$pl$c$v$yl(($)"➞ v$y$ll$

b??l?v?rd➞ boulevard

b@ch@➞ b****

Corrected
Solution:

function replaceVowel(str, c) {

returnstr.replace(/[aeoiu]/g, c);

Exercise 8:
Create a function to calculate the determinant of a 2 x 2 matrix.

[[a, b]]

[c, d]

The determinant of the above matrix is: ad - bc:

Example:
det(

[1, 1]

[2, 3]

]) ➞ 1

det(

[6, 4]

[2, 3]

]) ➞ 10

det([

[2, 4]

[4, 2]

]) ➞ -12

Corrected
Solution:

function det(matrix) {

return(matrice[0][0]*matrice[1][1]- matrice[1][0]*matrice[0][1]);

Exercise 9:
Write a function that returns the file extension.

Example:

getExtension(["file.html", "file.js"]) ➞ ["html", "js"]


getExtension(["image.jpg", "image.png", "image.gif"]) ➞ ["jpg", "png", "gif"]

getExtension(["file.pdf", "file.txt", "file.docx"]) ➞ ["pdf", "txt", "docx"]

Corrected
Solution:

function getExtension(files) {

returnfiles.map(file => file.split(".").pop())

You might also like