Ashraf Nazar c2558b3816
fix(Curriculum): ensure code that includes and is not equal to the fl… (#38497)
* fix(Curriculum): ensure code that includes and is not equal to the flat or flatMap methods do not fail the test suite

* Update curriculum/challenges/english/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.english.md

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* Update steamroller.english.md

Co-authored-by: Tom <20648924+moT01@users.noreply.github.com>
2020-04-23 14:59:58 -05:00

1.7 KiB

id, title, isRequired, challengeType, forumTopicId
id title isRequired challengeType forumTopicId
ab306dbdcc907c7ddfc30830 Steamroller true 5 16079

Description

Flatten a nested array. You must account for varying levels of nesting.

Instructions

Tests

tests:
  - text: <code>steamrollArray([[["a"]], [["b"]]])</code> should return <code>["a", "b"]</code>.
    testString: assert.deepEqual(steamrollArray([[["a"]], [["b"]]]), ["a", "b"]);
  - text: <code>steamrollArray([1, [2], [3, [[4]]]])</code> should return <code>[1, 2, 3, 4]</code>.
    testString: assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]);
  - text: <code>steamrollArray([1, [], [3, [[4]]]])</code> should return <code>[1, 3, 4]</code>.
    testString: assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]);
  - text: <code>steamrollArray([1, {}, [3, [[4]]]])</code> should return <code>[1, {}, 3, 4]</code>.
    testString: assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]);
  - text: Your solution should not use the <code>Array.prototype.flat()</code> or <code>Array.prototype.flatMap()</code> methods.
    testString: assert(!code.match(/\.\s*flat\s*\(/) && !code.match(/\.\s*flatMap\s*\(/));

Challenge Seed

function steamrollArray(arr) {
  return arr;
}

steamrollArray([1, [2], [3, [[4]]]]);

Solution

function steamrollArray(arr) {
  if (!Array.isArray(arr)) {
    return [arr];
  }
  var out = [];
  arr.forEach(function(e) {
    steamrollArray(e).forEach(function(v) {
      out.push(v);
    });
  });
  return out;
}