Add more ES6 examples

This commit is contained in:
antonlipilin
2021-10-06 18:20:52 +04:00
parent 7d27d15c0d
commit 2080afc740
8 changed files with 63 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
/**
* Count the number of elements in the array
* @param {Array} array Array of numbers
* @returns {number} The number of elements in the array
*/
const countLoop = (array) => {
let result = 0;
if (array.length === 0) {
return result;
}
for (let i = 0; i < array.length; i += 1) {
result += 1;
}
return result;
}
console.log(countLoop([3,5,8,11])) //4
console.log(countLoop([])) // 0

View File

@@ -0,0 +1,9 @@
/**
* Count the number of elements in the array
* @param {Array} array Array of numbers
* @returns {number} The number of elements in the array
*/
const countReduce = (array) => array.reduce((count, next) => count += 1, 0);
console.log(countReduce([5,8,11,13])) // 4
console.log(countReduce([]))// 0

View File

@@ -0,0 +1,23 @@
/**
* Calculate the largest number
* This solution works for arrays of any length
* @param {Array} array Array of numbers
* @returns {number} The argest number
*/
const maxLoop = (array) => {
let result = 0;
if (array.length === 0) {
return result;
}
for (let i = 0; i < array.length; i += 1) {
if (array[i] > result) {
result = array[i]
}
}
return result;
};
console.log(maxLoop([2,5,7,22,11])); // 22
console.log(maxLoop([])) // 0

View File

@@ -0,0 +1,10 @@
/**
* Calculate the largest number
* This solution works for arrays of any length
* @param {Array} array Array of numbers
* @returns {number} The argest number
*/
const maxReduce = (array) => array.reduce((curr, next) => next > curr ? next : curr, 0);
console.log(maxReduce([1,3,11,7])) // 11
console.log(maxReduce([])) // 0