let sum = 0
const numbers = [1,2,3,4,5,6,7,8,9,10]
for(let i = 0, len = numbers.length; i < len; i+=1) {
sum += numbers[i]
}
// => 55let product = 1
const numbers = [1,2,3,4,5,6,7,8,9,10]
for(let i = 0, len = numbers.length; i < len; i+=1) {
product *= numbers[i]
}
// => 3628800let sum = 0
let product = 1
sum = += numbers[i]
product *= numbers[i]High Order Function = Função que recebe uma função
Reduce recebe:
- Função
- Valor inicial
- Lista
(valorInicial, valorAtual) => valorInicial
const sum = (valorInicial, valorAtual) => valorInicial + valorAtual
const mult = (valorInicial, valorAtual) => valorInicial * valorAtual
const mapWithReduce = transform => (acc, value) => [...acc, transform(value)]
const numbers = [1,2,3,4,5,6,7,8,9,10]
reduce(sum, 0, numbers)
// => 55
reduce(product, 1, numbers)
// => 3628800const map = (transform, list) => {
let arr = [];
for(let i=0,len=list.length; i<len; i+=1) {
arr.push(transform(list[i], i))
}
return arr;
}
map(sum, list) // => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]const reduce = (fn, init, list) => {
let accumulate = init ? init : 1
for(let i=0,len=list.length; i<len; i+=1) {
accumulate = fn(accumulate, list[i])
}
return accumulate;
}
reduce(mult, 1, list) // => 3628800const mapWithReduce = (transform, list) => {
return reduce((acc, value) => [...acc, value], [], list)
}
mapWithReduce(sum, list) // => [2, 3, 4, 5, 6]