Skip to content

Instantly share code, notes, and snippets.

@rafaellucio
Created June 27, 2017 00:19
Show Gist options
  • Save rafaellucio/f14df329440e75fcbf8ecde29cb3db89 to your computer and use it in GitHub Desktop.
Save rafaellucio/f14df329440e75fcbf8ecde29cb3db89 to your computer and use it in GitHub Desktop.
Easynvest Dojo Javascript Functions Manipulação de Array

SOMA

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]
}

// => 55

PRODUTO

let 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]
}

// => 3628800

O que mudou?

let sum = 0
let product = 1

sum = += numbers[i]
product *= numbers[i]

Reduce

High Order Function = Função que recebe uma função

Reduce recebe:

  • Função
  • Valor inicial
  • Lista

Assinatura da função

(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)
// => 3628800

Map

const 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]

Reduce

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) // => 3628800

Map com Reduce

const mapWithReduce = (transform, list) => {
  return reduce((acc, value) => [...acc, value], [], list)
}

mapWithReduce(sum, list) // => [2, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment