JavaScript Course 7: Exercises: Difference between revisions
m Text replacement - "mlw-continue" to "code-continue" |
|||
Line 7: | Line 7: | ||
== Swapping Variables == | == Swapping Variables == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
let a = 'red'; | let a = 'red'; | ||
let b = 'blue'; | let b = 'blue'; | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(`a => ${a} \nb => ${b}`); | console.log(`a => ${a} \nb => ${b}`); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
a => red | a => red | ||
b => blue | b => blue | ||
</syntaxhighlight>In order to swaps the values of 'a' and 'b' we need a third variable<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>In order to swaps the values of 'a' and 'b' we need a third variable<syntaxhighlight lang="javascript" class="code-continue"> | ||
let buffer = a; | let buffer = a; | ||
a = b; | a = b; | ||
b = buffer; | b = buffer; | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(`a => ${a} \nb => ${b}`); | console.log(`a => ${a} \nb => ${b}`); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 27: | Line 27: | ||
== Max of Two Numbers == | == Max of Two Numbers == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
let a = 3; | let a = 3; | ||
let b = 5; | let b = 5; | ||
Line 35: | Line 35: | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
let maxNumber = max(a, b); | let maxNumber = max(a, b); | ||
console.log(maxNumber); | console.log(maxNumber); | ||
Line 43: | Line 43: | ||
== Landscape or Portrait == | == Landscape or Portrait == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function isLandscape(width, height) { | function isLandscape(width, height) { | ||
return width > height; // return (width > height); | return width > height; // return (width > height); | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(isLandscape(680, 200)); | console.log(isLandscape(680, 200)); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session" class=" | </syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue"> | ||
true | true | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(isLandscape(200, 400)); | console.log(isLandscape(200, 400)); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 59: | Line 59: | ||
== FizzBuzz Algorithm == | == FizzBuzz Algorithm == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
// Divisible by 3 => Fizz | // Divisible by 3 => Fizz | ||
// Divisible by 5 => Buzz | // Divisible by 5 => Buzz | ||
Line 75: | Line 75: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(fizzBuzz(99)); console.log(fizzBuzz(100)); console.log(fizzBuzz(105)); console.log(fizzBuzz(107)); | console.log(fizzBuzz(99)); console.log(fizzBuzz(100)); console.log(fizzBuzz(105)); console.log(fizzBuzz(107)); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 86: | Line 86: | ||
== Demerit Points == | == Demerit Points == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
// Speed limit = 70 km/h | // Speed limit = 70 km/h | ||
// Speed <= 70 => Ok | // Speed <= 70 => Ok | ||
Line 106: | Line 106: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
checkSpeed(71); checkSpeed(77); checkSpeed(125); checkSpeed(130); | checkSpeed(71); checkSpeed(77); checkSpeed(125); checkSpeed(130); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 116: | Line 116: | ||
== Even and Odd Numbers == | == Even and Odd Numbers == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function showNumbers(limit) { | function showNumbers(limit) { | ||
for (let i = 0; i <= limit; i++) { | for (let i = 0; i <= limit; i++) { | ||
Line 124: | Line 124: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function showNumbers(limit) { | function showNumbers(limit) { | ||
for (let i = 0; i <= limit; i++) { | for (let i = 0; i <= limit; i++) { | ||
Line 131: | Line 131: | ||
} | } | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
showNumbers(4); | showNumbers(4); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 142: | Line 142: | ||
== Count Truthy in an Array == | == Count Truthy in an Array == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function countTruthy(array) { | function countTruthy(array) { | ||
let counter = 0; | let counter = 0; | ||
Line 148: | Line 148: | ||
console.log(counter); | console.log(counter); | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
countTruthy([true, false, '', 'available', undefined, 1, null, 2, 'stop', 0]); | countTruthy([true, false, '', 'available', undefined, 1, null, 2, 'stop', 0]); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 155: | Line 155: | ||
== String Properties of an Object == | == String Properties of an Object == | ||
Create a function that will output only the String properties of an Object.<syntaxhighlight lang="javascript" class=" | Create a function that will output only the String properties of an Object.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function showStringProperties(obj) { | function showStringProperties(obj) { | ||
for (let key in obj) | for (let key in obj) | ||
Line 161: | Line 161: | ||
console.log(key, obj[key]); | console.log(key, obj[key]); | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
const movie = { | const movie = { | ||
title: 'a', | title: 'a', | ||
Line 176: | Line 176: | ||
== Sum of Multiples of 3 and 5 == | == Sum of Multiples of 3 and 5 == | ||
Let's assume there is a limit, for example 10, the multiple of 3 are 3, 6 and 9; and the multiples of 5 are 5 and 10.<syntaxhighlight lang="javascript" class=" | Let's assume there is a limit, for example 10, the multiple of 3 are 3, 6 and 9; and the multiples of 5 are 5 and 10.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function sumMultiplesOf3and5(limit) { | function sumMultiplesOf3and5(limit) { | ||
let sum = 0; | let sum = 0; | ||
Line 183: | Line 183: | ||
return sum; | return sum; | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(sumMultiplesOf3and5(10)); | console.log(sumMultiplesOf3and5(10)); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 190: | Line 190: | ||
== Grade of a Student == | == Grade of a Student == | ||
Grades: '''A'''[90-100], '''B'''[80-89], '''C'''[70-79], '''D'''[60-69], '''F'''[0-59].<syntaxhighlight lang="javascript" class=" | Grades: '''A'''[90-100], '''B'''[80-89], '''C'''[70-79], '''D'''[60-69], '''F'''[0-59].<syntaxhighlight lang="javascript" class="code-continue"> | ||
function calculateGrade(marks) { // marks is an Array | function calculateGrade(marks) { // marks is an Array | ||
let sum = 0; | let sum = 0; | ||
Line 204: | Line 204: | ||
return 'A'; | return 'A'; | ||
} | } | ||
</syntaxhighlight>By applying the single responsibility principle we can divide this function in to two smaller functions. Also we can simplify the part that calculates the average by the help of the <code>.reduce()</code> method.<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>By applying the single responsibility principle we can divide this function in to two smaller functions. Also we can simplify the part that calculates the average by the help of the <code>.reduce()</code> method.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function calculateGrade(marks) { | function calculateGrade(marks) { | ||
const average = calculateAverage(marks); | const average = calculateAverage(marks); | ||
Line 218: | Line 218: | ||
return array.reduce((sum, currentVal) => sum + currentVal) / array.length; | return array.reduce((sum, currentVal) => sum + currentVal) / array.length; | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
const marks = [80, 80, 50]; | const marks = [80, 80, 50]; | ||
console.log(calculateGrade(marks)); | console.log(calculateGrade(marks)); | ||
Line 226: | Line 226: | ||
== Show Stars == | == Show Stars == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function showStars(rows) { | function showStars(rows) { | ||
for (let row = 1; row <= rows; row++) { | for (let row = 1; row <= rows; row++) { | ||
Line 236: | Line 236: | ||
} | } | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
showStars(5); | showStars(5); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 247: | Line 247: | ||
== Show Primes == | == Show Primes == | ||
A prime numbers are these which have only two factors 1 and itself (prime number = цяло число).<syntaxhighlight lang="javascript" class=" | A prime numbers are these which have only two factors 1 and itself (prime number = цяло число).<syntaxhighlight lang="javascript" class="code-continue"> | ||
function showPrimes(limit) { | function showPrimes(limit) { | ||
for (let number = 2; number <= limit; number++) { | for (let number = 2; number <= limit; number++) { | ||
Line 261: | Line 261: | ||
} | } | ||
} | } | ||
</syntaxhighlight>Apply the single responsibility principle to the above function.<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>Apply the single responsibility principle to the above function.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function showPrimes(limit) { | function showPrimes(limit) { | ||
for (let number = 2; number <= limit; number++) | for (let number = 2; number <= limit; number++) | ||
Line 273: | Line 273: | ||
return true; | return true; | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
showPrimes(7); | showPrimes(7); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 283: | Line 283: | ||
== Address Object - list all Properties of an Object within a function == | == Address Object - list all Properties of an Object within a function == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
let address = { | let address = { | ||
street: '413-ta', | street: '413-ta', | ||
Line 294: | Line 294: | ||
console.log(key, obj[key]); | console.log(key, obj[key]); | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
showAddress(address); | showAddress(address); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Line 303: | Line 303: | ||
== Factory and Constructor Functions == | == Factory and Constructor Functions == | ||
Factory function to create the Address Object of the above exercises.<syntaxhighlight lang="javascript" class=" | Factory function to create the Address Object of the above exercises.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function cretateAddress(street, city, zipCode) { | function cretateAddress(street, city, zipCode) { | ||
return { | return { | ||
Line 311: | Line 311: | ||
} | } | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
let address1 = cretateAddress('RD 41', 'Pz', '4400'); | let address1 = cretateAddress('RD 41', 'Pz', '4400'); | ||
console.log(address1); | console.log(address1); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
{street: 'RD 41', city: 'Pz', zipCode: '4400'} | {street: 'RD 41', city: 'Pz', zipCode: '4400'} | ||
</syntaxhighlight>Constructor function to create the Address Object of the above exercises.<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>Constructor function to create the Address Object of the above exercises.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function Address(street, city, zipCode) { | function Address(street, city, zipCode) { | ||
this.street = street; | this.street = street; | ||
Line 322: | Line 322: | ||
this.zipCode = zipCode; | this.zipCode = zipCode; | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
let address2 = new Address('M4 415', 'Sf', '1715'); | let address2 = new Address('M4 415', 'Sf', '1715'); | ||
console.log(address2); | console.log(address2); | ||
</syntaxhighlight><syntaxhighlight lang="shell-session"> | </syntaxhighlight><syntaxhighlight lang="shell-session"> | ||
Address {street: 'M4 415', city: 'Sf', zipCode: '1715'} | Address {street: 'M4 415', city: 'Sf', zipCode: '1715'} | ||
</syntaxhighlight>Convert the Constructor function to ES6 Class.<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>Convert the Constructor function to ES6 Class.<syntaxhighlight lang="javascript" class="code-continue"> | ||
class Address { | class Address { | ||
constructor(street, city, zipCode) { | constructor(street, city, zipCode) { | ||
Line 335: | Line 335: | ||
} | } | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
let address2 = new Address('M4 415', 'Sf', '1715'); | let address2 = new Address('M4 415', 'Sf', '1715'); | ||
console.log(address2); | console.log(address2); | ||
Line 343: | Line 343: | ||
== Object Equality == | == Object Equality == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
class Address { | class Address { | ||
constructor(street, city, zipCode) { | constructor(street, city, zipCode) { | ||
Line 356: | Line 356: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Function to test whether the objects are equal. | Function to test whether the objects are equal. | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function areObjectsEqual(obj1, obj2) { | function areObjectsEqual(obj1, obj2) { | ||
if (Object.keys(obj1).length === Object.keys(obj1).length) { | if (Object.keys(obj1).length === Object.keys(obj1).length) { | ||
Line 367: | Line 367: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(areObjectsEqual(address1, address2)); | console.log(areObjectsEqual(address1, address2)); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 379: | Line 379: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(areObjectsEqual(address1, address2)); | console.log(areObjectsEqual(address1, address2)); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 385: | Line 385: | ||
false | false | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(areObjectsEqual(address1, address3)); | console.log(areObjectsEqual(address1, address3)); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 393: | Line 393: | ||
== Blog Post - Training for Object Literal Syntax == | == Blog Post - Training for Object Literal Syntax == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const post = { | const post = { | ||
title: "Post title", | title: "Post title", | ||
Line 408: | Line 408: | ||
== Constructor Function for Blog Post Objects == | == Constructor Function for Blog Post Objects == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function Post(title, body, author) { | function Post(title, body, author) { | ||
this.title = title; | this.title = title; | ||
Line 418: | Line 418: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const post1 = new Post('Title 1', "Body of title 1...", 'SZS'); | const post1 = new Post('Title 1', "Body of title 1...", 'SZS'); | ||
console.log(post1); | console.log(post1); | ||
Line 427: | Line 427: | ||
== Price Range Object == | == Price Range Object == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
let priceRanges = [ | let priceRanges = [ | ||
{label: "$", tooltip: "Inexpensive", minPerPerson: 0, maxPerPerson: 10}, | {label: "$", tooltip: "Inexpensive", minPerPerson: 0, maxPerPerson: 10}, | ||
Line 444: | Line 444: | ||
== Array from Range == | == Array from Range == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function arrayFromRange(min, max) { | function arrayFromRange(min, max) { | ||
const output = []; | const output = []; | ||
Line 451: | Line 451: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = arrayFromRange(-7, 4); | const numbers = arrayFromRange(-7, 4); | ||
console.log(numbers); | console.log(numbers); | ||
Line 461: | Line 461: | ||
== Includes in Array == | == Includes in Array == | ||
Create a replacement function for the <code>.includes()</code> method. | Create a replacement function for the <code>.includes()</code> method. | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function includes(array, searchedElement) { | function includes(array, searchedElement) { | ||
for (let element of array) | for (let element of array) | ||
Line 469: | Line 469: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = [1, 2, 3, 4]; | const numbers = [1, 2, 3, 4]; | ||
console.log(includes(numbers, 2), includes(numbers, 5)); | console.log(includes(numbers, 2), includes(numbers, 5)); | ||
Line 478: | Line 478: | ||
== Except - Exclude element from an array == | == Except - Exclude element from an array == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function except(array, excluded) { | function except(array, excluded) { | ||
const output = []; | const output = []; | ||
Line 488: | Line 488: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = [1, 2, 3, 4, 1, 1, 7, 1, 5, 1]; | const numbers = [1, 2, 3, 4, 1, 1, 7, 1, 5, 1]; | ||
const output = except(numbers, [1, 2, 7]); | const output = except(numbers, [1, 2, 7]); | ||
Line 500: | Line 500: | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function move(array, index, offset) { | function move(array, index, offset) { | ||
const newPossition = index + offset; | const newPossition = index + offset; | ||
Line 520: | Line 520: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = [1, 2, 3, 4]; | const numbers = [1, 2, 3, 4]; | ||
const output = move(numbers, 3, -2); | const output = move(numbers, 3, -2); | ||
Line 530: | Line 530: | ||
== Count Occurrences of an Value in an Array == | == Count Occurrences of an Value in an Array == | ||
By using <code>for.. of..</code> loop.<syntaxhighlight lang="javascript" class=" | By using <code>for.. of..</code> loop.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function countOccurances(array, searchedElement) { | function countOccurances(array, searchedElement) { | ||
let count = 0; | let count = 0; | ||
Line 538: | Line 538: | ||
return count; | return count; | ||
} | } | ||
</syntaxhighlight>By using <code>.reduce()</code> method;<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>By using <code>.reduce()</code> method;<syntaxhighlight lang="javascript" class="code-continue"> | ||
function countOccurances(array, searchedElement) { | function countOccurances(array, searchedElement) { | ||
return array.reduce((count, currentValue) => count += (currentValue === searchedElement) ? 1 : 0, 0); | return array.reduce((count, currentValue) => count += (currentValue === searchedElement) ? 1 : 0, 0); | ||
Line 544: | Line 544: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = [1, 2, 3, 1, 2, 4, 1, 5, 4, 2, 3, 3, 8, 1, 9]; | const numbers = [1, 2, 3, 1, 2, 4, 1, 5, 4, 2, 3, 3, 8, 1, 9]; | ||
const output = countOccurances(numbers, 2); | const output = countOccurances(numbers, 2); | ||
Line 555: | Line 555: | ||
== Get max Occurrences of an Value in an Array == | == Get max Occurrences of an Value in an Array == | ||
By using <code>for.. in..</code> loop. | By using <code>for.. in..</code> loop. | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function getMax(array) { | function getMax(array) { | ||
if (array.length === 0) return undefined; | if (array.length === 0) return undefined; | ||
Line 569: | Line 569: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
By using <code>for.. of..</code> loop. | By using <code>for.. of..</code> loop. | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
function getMax(array) { | function getMax(array) { | ||
let max = 0; | let max = 0; | ||
Line 586: | Line 586: | ||
return array.reduce((max, currentValue) => (max > currentValue) ? max : currentValue); | return array.reduce((max, currentValue) => (max > currentValue) ? max : currentValue); | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
function getMax(array) { | function getMax(array) { | ||
return array.reduce((max, currentValue) => (max > currentValue) ? max : currentValue, undefined); | return array.reduce((max, currentValue) => (max > currentValue) ? max : currentValue, undefined); | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = [1, 2, 3, 1, 2, 4, 11, 5, 4, 2, 3, 3, 8, 1, 9]; | const numbers = [1, 2, 3, 1, 2, 4, 11, 5, 4, 2, 3, 3, 8, 1, 9]; | ||
const max = getMax(numbers); | const max = getMax(numbers); | ||
Line 601: | Line 601: | ||
== Sort an Array of Movie Objects == | == Sort an Array of Movie Objects == | ||
Output all the movies in 2018 with rating > 4, sort them by their rating in descending order and display only title property on the console.<syntaxhighlight lang="javascript" class=" | Output all the movies in 2018 with rating > 4, sort them by their rating in descending order and display only title property on the console.<syntaxhighlight lang="javascript" class="code-continue"> | ||
const movies = [ | const movies = [ | ||
{title: 'a', year: 2018, rating: 4.5}, | {title: 'a', year: 2018, rating: 4.5}, | ||
Line 608: | Line 608: | ||
{title: 'd', year: 2017, rating: 4.5} | {title: 'd', year: 2017, rating: 4.5} | ||
]; | ]; | ||
</syntaxhighlight>By using <code>for.. of..</code> loop and <code>if</code> condition.<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>By using <code>for.. of..</code> loop and <code>if</code> condition.<syntaxhighlight lang="javascript" class="code-continue"> | ||
function getMovies(movies = [], ofYear = 2018, minRating = 4) { | function getMovies(movies = [], ofYear = 2018, minRating = 4) { | ||
const output = []; | const output = []; | ||
Line 618: | Line 618: | ||
} | } | ||
const titles = getMovies(movies, 2018, 4); | const titles = getMovies(movies, 2018, 4); | ||
</syntaxhighlight>By using <code>.filter()</code>, <code>.sort()</code>, <code>reverse()</code> and <code>map()</code> methods.<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>By using <code>.filter()</code>, <code>.sort()</code>, <code>reverse()</code> and <code>map()</code> methods.<syntaxhighlight lang="javascript" class="code-continue"> | ||
const titles = movies | const titles = movies | ||
.filter(movie => (movie.year === 2018 && movie.rating > 4)) | .filter(movie => (movie.year === 2018 && movie.rating > 4)) | ||
Line 624: | Line 624: | ||
.reverse() | .reverse() | ||
.map(movie => movie.title); | .map(movie => movie.title); | ||
</syntaxhighlight>By reversing the order within the <code>.sort()</code> method, and skip <code>.reverse()</code> method.<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>By reversing the order within the <code>.sort()</code> method, and skip <code>.reverse()</code> method.<syntaxhighlight lang="javascript" class="code-continue"> | ||
const titles = movies | const titles = movies | ||
.filter(movie => (movie.year === 2018 && movie.rating > 4)) | .filter(movie => (movie.year === 2018 && movie.rating > 4)) | ||
.sort((a, b) => b.rating - a.rating) | .sort((a, b) => b.rating - a.rating) | ||
.map(movie => movie.title); | .map(movie => movie.title); | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(titles); | console.log(titles); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 639: | Line 639: | ||
In this exercise we will create a function that returns the sum of its arguments. They could be passed as an array or as separate arguments. | In this exercise we will create a function that returns the sum of its arguments. They could be passed as an array or as separate arguments. | ||
'''By using rhe Arguments special object and a <code>for.. of..</code> loop.'''<syntaxhighlight lang="javascript" class=" | '''By using rhe Arguments special object and a <code>for.. of..</code> loop.'''<syntaxhighlight lang="javascript" class="code-continue"> | ||
function sumArguments() { | function sumArguments() { | ||
let args = []; | let args = []; | ||
Line 651: | Line 651: | ||
return sum; | return sum; | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
const sumArray = sumArguments([1, 2, 3, 4]); | const sumArray = sumArguments([1, 2, 3, 4]); | ||
const sumArgs = sumArguments(1, 2, 3, 4); | const sumArgs = sumArguments(1, 2, 3, 4); | ||
Line 658: | Line 658: | ||
<syntaxhighlight lang="shell-session"> | <syntaxhighlight lang="shell-session"> | ||
10 10 | 10 10 | ||
</syntaxhighlight>'''By using the Arguments special object and the <code>.reduce()</code> method.'''<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>'''By using the Arguments special object and the <code>.reduce()</code> method.'''<syntaxhighlight lang="javascript" class="code-continue"> | ||
function sumArguments() { | function sumArguments() { | ||
let args = []; | let args = []; | ||
Line 667: | Line 667: | ||
return args.reduce((sum, currentValue) => sum + currentValue); | return args.reduce((sum, currentValue) => sum + currentValue); | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
const sumArray = sumArguments([1, 2, 3, 4]); | const sumArray = sumArguments([1, 2, 3, 4]); | ||
const sumArgs = sumArguments(1, 2, 3, 4); | const sumArgs = sumArguments(1, 2, 3, 4); | ||
Line 674: | Line 674: | ||
<syntaxhighlight lang="shell-session"> | <syntaxhighlight lang="shell-session"> | ||
10 10 | 10 10 | ||
</syntaxhighlight>'''By using the ...Rest operator and the <code>.reduce()</code> method.'''<syntaxhighlight lang="javascript" class=" | </syntaxhighlight>'''By using the ...Rest operator and the <code>.reduce()</code> method.'''<syntaxhighlight lang="javascript" class="code-continue"> | ||
function sumRest(...args) { | function sumRest(...args) { | ||
if (args.length === 1 && Array.isArray(args[0])) args = [...args[0]]; | if (args.length === 1 && Array.isArray(args[0])) args = [...args[0]]; | ||
return args.reduce((sum, currentValue) => sum + currentValue); | return args.reduce((sum, currentValue) => sum + currentValue); | ||
} | } | ||
</syntaxhighlight><syntaxhighlight lang="javascript" class=" | </syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue"> | ||
const sumArray = sumRest([1, 2, 3, 4]); | const sumArray = sumRest([1, 2, 3, 4]); | ||
const sumArgs = sumRest(1, 2, 3, 4); | const sumArgs = sumRest(1, 2, 3, 4); | ||
Line 689: | Line 689: | ||
== Area of Circle - Using a Getter Method == | == Area of Circle - Using a Getter Method == | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const circle = { | const circle = { | ||
radius: 2, | radius: 2, | ||
Line 697: | Line 697: | ||
}; | }; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
console.log(circle.area); | console.log(circle.area); | ||
circle.radius = 4; | circle.radius = 4; | ||
Line 718: | Line 718: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = [1, 2, 3, 1, 4]; | const numbers = [1, 2, 3, 1, 4]; | ||
try { | try { | ||
Line 731: | Line 731: | ||
2 | 2 | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
const numbers = false; // or anything else different from array | const numbers = false; // or anything else different from array | ||
try { | try { |
Latest revision as of 07:30, 26 September 2022
References
- Code with Mosh: The Ultimate JavaScript Mastery Series – Part 1
- W3School: JavaScript Tutorial
Swapping Variables
let a = 'red';
let b = 'blue';
console.log(`a => ${a} \nb => ${b}`);
a => red
b => blue
In order to swaps the values of 'a' and 'b' we need a third variable
let buffer = a;
a = b;
b = buffer;
console.log(`a => ${a} \nb => ${b}`);
a => blue
b => red
Max of Two Numbers
let a = 3;
let b = 5;
function max(number1, number2) {
return (number1 > number2) ? number1 : number2;
}
let maxNumber = max(a, b);
console.log(maxNumber);
5
Landscape or Portrait
function isLandscape(width, height) {
return width > height; // return (width > height);
}
console.log(isLandscape(680, 200));
true
console.log(isLandscape(200, 400));
false
FizzBuzz Algorithm
// Divisible by 3 => Fizz
// Divisible by 5 => Buzz
// Divisible by 3 and 5 => FizzBuzz
// Not divisible by 3 or 5 => return the input number
// If the argument is not a number => NaN
function fizzBuzz(input) {
if (typeof input !== 'number') return NaN;
if (input % 3 === 0 && input % 5 === 0) return 'FizzBuss';
if (input % 3 === 0) return 'Fizz';
if (input % 5 === 0) return 'Buzz';
return input;
}
console.log(fizzBuzz(99)); console.log(fizzBuzz(100)); console.log(fizzBuzz(105)); console.log(fizzBuzz(107));
Fizz
Buzz
FizzBuzz
107
Demerit Points
// Speed limit = 70 km/h
// Speed <= 70 => Ok
// For every 5 km above speed linit => add 1 pont
// So: Speed < 75 => Ok
// Speed = 75 => 1 point
// Speed = 80 => 2 points
// Speed = 85 => 3 points
// 12 points => License suspended
function checkSpeed(speed) {
const speedLimit = 70;
const kmPerPoint = 5;
const points = Math.floor((speed - speedLimit) / kmPerPoint);
if (points === 0) console.log('Ok');
else if (points >= 12) console.log('License suspended');
else console.log('Poinst', points);
}
checkSpeed(71); checkSpeed(77); checkSpeed(125); checkSpeed(130);
Ok
Points 1
Points 11
License suspended
Even and Odd Numbers
function showNumbers(limit) {
for (let i = 0; i <= limit; i++) {
if (i % 2 === 0) console.log(i, 'EVEN');
else console.log(i, 'ODD');
}
}
function showNumbers(limit) {
for (let i = 0; i <= limit; i++) {
const message = (i % 2 === 0) ? 'EVEN' : 'ODD';
console.log(i, message);
}
}
showNumbers(4);
0 'EVEN'
1 'ODD'
2 'EVEN'
3 'ODD'
4 'EVEN'
Count Truthy in an Array
function countTruthy(array) {
let counter = 0;
for (let value of array) if (value) counter++;
console.log(counter);
}
countTruthy([true, false, '', 'available', undefined, 1, null, 2, 'stop', 0]);
5
String Properties of an Object
Create a function that will output only the String properties of an Object.
function showStringProperties(obj) {
for (let key in obj)
if (typeof obj[key] === 'string')
console.log(key, obj[key]);
}
const movie = {
title: 'a',
releaseYear: 2018,
rating: 4.5,
director: 'b'
};
showStringProperties(movie);
title a
director b
Sum of Multiples of 3 and 5
Let's assume there is a limit, for example 10, the multiple of 3 are 3, 6 and 9; and the multiples of 5 are 5 and 10.
function sumMultiplesOf3and5(limit) {
let sum = 0;
for (let i = 0; i <= limit; i++)
sum += (i % 3 === 0 || i % 5 === 0) ? i : 0;
return sum;
}
console.log(sumMultiplesOf3and5(10));
33
Grade of a Student
Grades: A[90–100], B[80–89], C[70–79], D[60–69], F[0–59].
function calculateGrade(marks) { // marks is an Array
let sum = 0;
for (let mark of marks) sum += mark;
let averageGrade = sum / marks.length;
if (averageGrade < 60) return 'F';
if (averageGrade < 70) return 'D';
if (averageGrade < 80) return 'C';
if (averageGrade < 90) return 'B';
return 'A';
}
By applying the single responsibility principle we can divide this function in to two smaller functions. Also we can simplify the part that calculates the average by the help of the .reduce()
method.
function calculateGrade(marks) {
const average = calculateAverage(marks);
if (average < 60) return 'F';
if (average < 70) return 'D';
if (average < 80) return 'C';
if (average < 90) return 'B';
return 'A';
}
function calculateAverage(array) {
return array.reduce((sum, currentVal) => sum + currentVal) / array.length;
}
const marks = [80, 80, 50];
console.log(calculateGrade(marks));
C
Show Stars
function showStars(rows) {
for (let row = 1; row <= rows; row++) {
let pattern = '';
for (let i = 1; i <= row; i++) { // This is what we call a Nested Loop
pattern = pattern + '*';
}
console.log(pattern);
}
}
showStars(5);
*
**
***
****
*****
Show Primes
A prime numbers are these which have only two factors 1 and itself (prime number = цяло число).
function showPrimes(limit) {
for (let number = 2; number <= limit; number++) {
let isPrime = true;
for (let factor = 2; factor < number; factor++) {
if (number % factor === 0) {
isPrime = false;
break; // Jum out of this loop because we already know this is not Prime number
}
}
if (isPrime) console.log(number);
}
}
Apply the single responsibility principle to the above function.
function showPrimes(limit) {
for (let number = 2; number <= limit; number++)
if (isPrime(number)) console.log(number);
}
function isPrime(number) {
for (let factor = 2; factor < number; factor++)
if (number % factor === 0)
return false;
return true;
}
showPrimes(7);
2
3
5
7
Address Object – list all Properties of an Object within a function
let address = {
street: '413-ta',
city: 'Sofia',
zipCode: 1715
};
function showAddress(obj) {
for (let key in obj)
console.log(key, obj[key]);
}
showAddress(address);
street 413-ta
city Sofia
zipCode 1715
Factory and Constructor Functions
Factory function to create the Address Object of the above exercises.
function cretateAddress(street, city, zipCode) {
return {
street,
city,
zipCode
}
}
let address1 = cretateAddress('RD 41', 'Pz', '4400');
console.log(address1);
{street: 'RD 41', city: 'Pz', zipCode: '4400'}
Constructor function to create the Address Object of the above exercises.
function Address(street, city, zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}
let address2 = new Address('M4 415', 'Sf', '1715');
console.log(address2);
Address {street: 'M4 415', city: 'Sf', zipCode: '1715'}
Convert the Constructor function to ES6 Class.
class Address {
constructor(street, city, zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}
}
let address2 = new Address('M4 415', 'Sf', '1715');
console.log(address2);
Address {street: 'M4 415', city: 'Sf', zipCode: '1715'}
Object Equality
class Address {
constructor(street, city, zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}
}
let address1 = new Address('a', 'b', 'c');
let address2 = new Address('a', 'b', 'c');
let address3 = address1;
Function to test whether the objects are equal.
function areObjectsEqual(obj1, obj2) {
if (Object.keys(obj1).length === Object.keys(obj1).length) {
for (let key in obj1)
if (obj1[key] !== obj2[key])
return false;
return true;
}
return false;
}
console.log(areObjectsEqual(address1, address2));
true
Function to test whether the objects are same – refer to the same object in the memory.
function areObjectsSame(obj1, obj2) {
return obj1 === obj2;
}
console.log(areObjectsEqual(address1, address2));
false
console.log(areObjectsEqual(address1, address3));
true
Blog Post – Training for Object Literal Syntax
const post = {
title: "Post title",
body: "Post body...",
author: "Post author",
views: 153,
comments: [
{author: "Comment 1 author", body: "Comment 1 body..."},
{author: "Comment 2 author", body: "Comment 2 body..."}
],
isLive: true
};
Constructor Function for Blog Post Objects
function Post(title, body, author) {
this.title = title;
this.body = body;
this.author = author;
this.views = 0;
this.comments = [];
this.isLive = false;
}
const post1 = new Post('Title 1', "Body of title 1...", 'SZS');
console.log(post1);
Post {title: 'Title 1', body: 'Body of title 1...', author: 'SZS', views: 0, comments: Array(0), isLive: false}
Price Range Object
let priceRanges = [
{label: "$", tooltip: "Inexpensive", minPerPerson: 0, maxPerPerson: 10},
{label: "$$", tooltip: "Moderate", minPerPerson: 11, maxPerPerson: 20},
{label: "$$$", tooltip: "Expensive", minPerPerson: 21, maxPerPerson: 50}
];
let restaurants = [
{name: 'a', averagePerPerson: 5},
{name: 'b', averagePerPerson: 15},
{name: 'c', averagePerPerson: 25}
];
// We can create a filter as intersection of these 2 objects
Array from Range
function arrayFromRange(min, max) {
const output = [];
for (let i = min; i <= max; i++) output.push(i);
return output;
}
const numbers = arrayFromRange(-7, 4);
console.log(numbers);
(12) [-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
Includes in Array
Create a replacement function for the .includes()
method.
function includes(array, searchedElement) {
for (let element of array)
if (element === searchedElement)
return true;
return false;
}
const numbers = [1, 2, 3, 4];
console.log(includes(numbers, 2), includes(numbers, 5));
true false
Except – Exclude element from an array
function except(array, excluded) {
const output = [];
for (let element of array) {
if (!excluded.includes(element))
output.push(element);
}
return output;
}
const numbers = [1, 2, 3, 4, 1, 1, 7, 1, 5, 1];
const output = except(numbers, [1, 2, 7]);
console.log(output);
(3) [3, 4, 5]
Moving an Element in an Array
function move(array, index, offset) {
const newPossition = index + offset;
if (newPossition >= array.length || newPossition < 0) {
console.error('Invalid offset.');
return;
}
const output = [...array];
// const elementToMove = output[index]; output.splice(index, 1);
// The above lines could be replaced by the follow expression, because the .splice() method
// modifies the original array and returns an array of the removed elements [we need the first]
const elementToMove = output.splice(index, 1)[0];
output.splice(newPossition, 0, elementToMove);
return output;
}
const numbers = [1, 2, 3, 4];
const output = move(numbers, 3, -2);
console.log(output);
(4) [1, 4, 2, 3]
Count Occurrences of an Value in an Array
By using for.. of..
loop.
function countOccurances(array, searchedElement) {
let count = 0;
for (let element of array)
if (element == searchedElement)
count++;
return count;
}
By using .reduce()
method;
function countOccurances(array, searchedElement) {
return array.reduce((count, currentValue) => count += (currentValue === searchedElement) ? 1 : 0, 0);
}
const numbers = [1, 2, 3, 1, 2, 4, 1, 5, 4, 2, 3, 3, 8, 1, 9];
const output = countOccurances(numbers, 2);
console.log(output);
3
Get max Occurrences of an Value in an Array
By using for.. in..
loop.
function getMax(array) {
if (array.length === 0) return undefined;
let max = array[0];
for (let i = 1; i < array.length; i++)
if (array[i] > max)
max = array[i];
return max;
}
By using for.. of..
loop.
function getMax(array) {
let max = 0;
for (let element of array)
if (element > max)
max = element;
return (max) ? max : undefined;
}
By using .reduce()
method.
function getMax(array) {
if (array.length === 0) return undefined;
return array.reduce((max, currentValue) => (max > currentValue) ? max : currentValue);
}
function getMax(array) {
return array.reduce((max, currentValue) => (max > currentValue) ? max : currentValue, undefined);
}
const numbers = [1, 2, 3, 1, 2, 4, 11, 5, 4, 2, 3, 3, 8, 1, 9];
const max = getMax(numbers);
console.log(max);
11
Sort an Array of Movie Objects
Output all the movies in 2018 with rating > 4, sort them by their rating in descending order and display only title property on the console.
const movies = [
{title: 'a', year: 2018, rating: 4.5},
{title: 'b', year: 2018, rating: 4.7},
{title: 'c', year: 2018, rating: 3},
{title: 'd', year: 2017, rating: 4.5}
];
By using for.. of..
loop and if
condition.
function getMovies(movies = [], ofYear = 2018, minRating = 4) {
const output = [];
for (let movie of movies) {
if (movie.year === ofYear && movie.rating > minRating)
output.push(movie.title);
}
return output.sort().reverse();
}
const titles = getMovies(movies, 2018, 4);
By using .filter()
, .sort()
, reverse()
and map()
methods.
const titles = movies
.filter(movie => (movie.year === 2018 && movie.rating > 4))
.sort((a, b) => a.rating - b.rating)
.reverse()
.map(movie => movie.title);
By reversing the order within the .sort()
method, and skip .reverse()
method.
const titles = movies
.filter(movie => (movie.year === 2018 && movie.rating > 4))
.sort((a, b) => b.rating - a.rating)
.map(movie => movie.title);
console.log(titles);
(2) ['b', 'a']
Sum of Arguments
In this exercise we will create a function that returns the sum of its arguments. They could be passed as an array or as separate arguments.
By using rhe Arguments special object and a for.. of..
loop.
function sumArguments() {
let args = [];
let sum = 0;
if (Array.isArray(arguments[0])) args = [...arguments[0]];
else args = [...arguments];
for (let i of args) sum += i;
return sum;
}
const sumArray = sumArguments([1, 2, 3, 4]);
const sumArgs = sumArguments(1, 2, 3, 4);
console.log(sumArray, sumArgs);
10 10
By using the Arguments special object and the .reduce()
method.
function sumArguments() {
let args = [];
if (Array.isArray(arguments[0])) args = [...arguments[0]];
else args = [...arguments];
return args.reduce((sum, currentValue) => sum + currentValue);
}
const sumArray = sumArguments([1, 2, 3, 4]);
const sumArgs = sumArguments(1, 2, 3, 4);
console.log(sumArray, sumArgs);
10 10
By using the …Rest operator and the .reduce()
method.
function sumRest(...args) {
if (args.length === 1 && Array.isArray(args[0])) args = [...args[0]];
return args.reduce((sum, currentValue) => sum + currentValue);
}
const sumArray = sumRest([1, 2, 3, 4]);
const sumArgs = sumRest(1, 2, 3, 4);
console.log(sumArray, sumArgs);
10 10
Area of Circle – Using a Getter Method
const circle = {
radius: 2,
get area() {
return this.radius * this.radius * Math.PI;
}
};
console.log(circle.area);
circle.radius = 4;
console.log(circle.area);
12.566370614359172
50.265482457436690
Error Handling
function countOccurrences(array, searchElement) {
if (!Array.isArray(array))
throw new Error('Invalid array!');
return array.reduce((accumulator, current) => {
return (current === searchElement) ? accumulator + 1 : accumulator + 0;
}, 0);
}
const numbers = [1, 2, 3, 1, 4];
try {
const count = countOccurrences(numbers, 1);
console.log(count);
}
catch (e) {
console.log(e.message);
}
2
const numbers = false; // or anything else different from array
try {
const count = countOccurrences(numbers, 1);
console.log(count);
}
catch (e) {
console.log(e.message);
}
Invalid array!