Skip to content

Instantly share code, notes, and snippets.

@Dpalazzari
Last active May 28, 2019 18:25
Show Gist options
  • Save Dpalazzari/9c774474dd7040245e2f9c7cacf7ec98 to your computer and use it in GitHub Desktop.
Save Dpalazzari/9c774474dd7040245e2f9c7cacf7ec98 to your computer and use it in GitHub Desktop.
flatten

Disclaimer

I have done this before in a personal challenges repository. For your convience, I copied the code to this gist, but the source repo can be found here.

Ruby

# ruby class
class Flatten

# subject to further refactoring

  def condense_array(arr, final_array = [])
    arr.each do |element|
      if element.class == Array
        construct_array(element, final_array)
      else
        final_array << element
      end
    end
    final_array
  end

  def construct_array(element, final_array)
    element.each do |el|
      if el.class == Array
        condense_array(el, final_array)
      else
        final_array << el
      end
    end
  end

end

### tests

    
require 'minitest/autorun'
require 'minitest/emoji'
require 'flatten.rb'

class FlattenTest < Minitest::Test

  def setup
    @flatten = Flatten.new
  end

  def test_it_exists
    assert @flatten
  end

  def test_it_flattens_and_array_within_an_array
    array  = [2, [1,2]]
    result = @flatten.condense_array(array)
    assert_equal [2, 1, 2], result
  end

  def test_it_continues_to_flatten_nested_arrays
    array  = [2, [1,2,[3,4]]]
    result = @flatten.condense_array(array)
    assert_equal [2, 1, 2, 3, 4], result
  end

  def test_it_flattens_an_insanely_nested_array
    array  = [2, [1,2,[3,[4, 5]]], [1, [3,4]]]
    result = @flatten.condense_array(array)
    assert_equal [2, 1, 2, 3, 4, 5, 1, 3, 4], result
  end

end

Javascript

// flatten function
module.exports = function flattenArray(arr){
  var finalArray = [].concat.apply([], arr)
  for(i = 0; i < finalArray.length; i++){
    if(finalArray[i].length){
      var finalArray = flattenArray(finalArray)
    }
  }
  return finalArray
}

// tests
const assert    = require('chai').assert;
const flatten   = require('../javascriptChallenges/flattenArray');

describe('Flatten challenge', function(){
  it('flattens a simple nested array', function(){
    var array = [2, [1, 3]]
    var result = flatten(array)
    assert.deepEqual(result, [2, 1, 3])
    assert.typeOf(result, 'array')
  })

  it('flattens a more complex array', function(){
    var array = [2, [1, 3, [4, 5]]]
    var result = flatten(array)
    assert.deepEqual(result, [2, 1, 3, 4, 5])
    assert.typeOf(result, 'array')
  })

  it('flattens a very complex array', function(){
    var array = [2, [1, 3, [4, 5]], 6, [7, [8, [9, 10]]]]
    var result = flatten(array)
    assert.deepEqual(result, [2, 1, 3, 4, 5, 6, 7, 8, 9, 10])
    assert.typeOf(result, 'array')
  })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment