Skip to content

Instantly share code, notes, and snippets.

@amuntasim
Created February 8, 2018 03:49
Show Gist options
  • Save amuntasim/d7cf052933fccca956bfc816f39f69d5 to your computer and use it in GitHub Desktop.
Save amuntasim/d7cf052933fccca956bfc816f39f69d5 to your computer and use it in GitHub Desktop.

Revisions

  1. amuntasim created this gist Feb 8, 2018.
    33 changes: 33 additions & 0 deletions ruby_custom_flatten.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    class FlattenTest
    def self.custom_flatten(array, result = [])
    array.each do |item|
    if item.is_a? Array
    custom_flatten(item, result)
    else
    result << item
    end
    end
    result
    end
    end

    RSpec.describe FlattenTest do

    context '.custom_flatten' do
    it 'should flatten array of arrays' do
    expected = [1, 2, 3, 4, 5, 6]
    expect(FlattenTest.custom_flatten([[1, 2], 3, [4, 5, 6]])).to eq expected
    end

    it 'should flatten nested array of arrays' do
    expected = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    expect(FlattenTest.custom_flatten([[1, 2], 3, [4, 5, [6, [7, 8], 9]]])).to eq expected
    end

    it 'should return already flatten array' do
    expected = [1, 2, 3, 4]
    expect(FlattenTest.custom_flatten(expected)).to eq expected
    end

    end
    end