freeCodeCamp/curriculum/challenges/portuguese/02-javascript-algorithms-an.../functional-programming/add-elements-to-the-end-of-...

2.7 KiB

id title challengeType videoUrl localeTitle
587d7da9367417b2b2512b67 Add Elements to the End of an Array Using concat Instead of push 1 Adicionar elementos ao final de um array usando concat Em vez de push

Description

A programação funcional é toda sobre a criação e uso de funções não mutantes. O último desafio introduziu o método concat como uma maneira de combinar matrizes em um novo sem alterar os arrays originais. Compare concat no método push . Push adiciona um item ao final do mesmo array em que é chamado, o que modifica esse array. Aqui está um exemplo:
var arr = [1, 2, 3];
arr.push ([4, 5, 6]);
// arr é alterado para [1, 2, 3, [4, 5, 6]]
// Não é a maneira funcional de programação
Concat oferece uma maneira de adicionar novos itens ao final de um array sem nenhum efeito colateral mutante.

Instructions

Altere a função nonMutatingPush para que use a concat para adicionar newItem ao final do original vez de push . A função deve retornar uma matriz.

Tests

tests:
  - text: Seu código deve usar o método <code>concat</code> .
    testString: 'assert(code.match(/\.concat/g), "Your code should use the <code>concat</code> method.");'
  - text: Seu código não deve usar o método <code>push</code> .
    testString: 'assert(!code.match(/\.push/g), "Your code should not use the <code>push</code> method.");'
  - text: O <code>first</code> array não deve mudar.
    testString: 'assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]), "The <code>first</code> array should not change.");'
  - text: O <code>second</code> array não deve mudar.
    testString: 'assert(JSON.stringify(second) === JSON.stringify([4, 5]), "The <code>second</code> array should not change.");'
  - text: '<code>nonMutatingPush([1, 2, 3], [4, 5])</code> deve retornar <code>[1, 2, 3, 4, 5]</code> .'
    testString: 'assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]), "<code>nonMutatingPush([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.");'

Challenge Seed

function nonMutatingPush(original, newItem) {
  // Add your code below this line
  return original.push(newItem);

  // Add your code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);

Solution

// solution required