Higher-Order Functions
Functions, in this context, are first-class citizens. They can be stored in variables, passed as arguments, and returned as values.
a.map(f)
Implement the following functions as described:
max(a0, a1, ..., ak)
returns the maximum of the arguments provided usingMath.max()
, the spread syntax, and the rest parameter syntax.range(a, b)
returns the range of integers usingArray.from()
.rand(a, b)
returns a random integer in usingMath.random()
.randoms(n, a, b)
returns an array of elements sampled randomly in the range usingArray.map()
.factorial(n)
returns the factorial of , that is, usingArray.reduce()
.divisors(n)
returns the divisors of usingArray.filter()
.isPrime(n)
returns whether is prime or not usingArray.every()
.primeProduct(a, b)
returns the product of the prime integers in usingArray.filter()
andArray.reduce()
.factorialSum(a, b)
returns the total of the factorials of the integers in usingArray.map()
andArray.reduce()
.tally(array)
returns the running total of an array usingArray.reduce()
and the spread syntax.reverse(array)
returns the reverse of an array usingArray.reduce()
and the spread syntax.
Test and validate your functions using the following script and sample output:
const array = range(1, 20);
console.log("Max:", max(7, 1, 2, -3));
console.log("Max:", max(1, 5, -10, 23, 0, -7, 18));
console.log("Range 1 to 10:", range(1, 10));
console.log("Random 20, 1 to 100:", randoms(20, 1, 100));
console.log("Factorial 0:", factorial(0));
console.log("Factorial 5:", factorial(5));
console.log("Divisors 1:", divisors(1));
console.log("Divisors 7:", divisors(7));
console.log("Divisors 12:", divisors(12));
console.log("Prime 1:", isPrime(1));
console.log("Prime 23:", isPrime(23));
console.log("Primes < 100:", range(1, 100).filter(isPrime));
console.log("PrimeProduct 1 to 100:", primeProduct(1, 100));
console.log("FactorialSum 1 to 100:", factorialSum(1, 100));
console.log("Tally 1 to 20:", tally(array));
console.log("Reverse 1 to 20:", reverse(array));
Max: 7
Max: 23
Range 1 to 10: [
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
]
Random 20, 1 to 100: [
88, 69, 98, 73, 64, 60, 7,
94, 52, 36, 90, 38, 97, 4,
1, 42, 63, 83, 54, 96
]
Factorial 0: 1n
Factorial 5: 120n
Divisors 1: [ 1 ]
Divisors 7: [ 1, 7 ]
Divisors 12: [ 1, 2, 3, 4, 6, 12 ]
Prime 1: false
Prime 23: true
Primes < 100: [
2, 3, 5, 7, 11, 13, 17, 19,
23, 29, 31, 37, 41, 43, 47, 53,
59, 61, 67, 71, 73, 79, 83, 89,
97
]
PrimeProduct 1 to 100: 2305567963945518424753102147331756070n
FactorialSum 1 to 100: 94269001683709979260859834124473539872070722613982672442938359305624678223479506023400294093599136466986609124347432647622826870038220556442336528920420940313n
Tally 1 to 20: [
1, 3, 6, 10, 15, 21, 28,
36, 45, 55, 66, 78, 91, 105,
120, 136, 153, 171, 190, 210
]
Reverse 1 to 20: [
20, 19, 18, 17, 16, 15, 14,
13, 12, 11, 10, 9, 8, 7,
6, 5, 4, 3, 2, 1
]