Created
April 28, 2016 16:19
-
-
Save virolea/a588f2cf85b6faca04e56fcf5cd73b65 to your computer and use it in GitHub Desktop.
Flatten an array of nest arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def flatten(array) | |
| return "Input must be an array" if !array.kind_of?(Array) | |
| array.reduce([]) do |res, el| | |
| Array === el ? res + flatten(el) : res << el | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'flatten' | |
| describe '#flatten' do | |
| it "must raise an error if the input is not an array" do | |
| input = "string" | |
| expect(flatten(input)).to eq("Input must be an array") | |
| end | |
| it "must raise an error if the input is null" do | |
| input = nil | |
| expect(flatten(input)).to eq("Input must be an array") | |
| end | |
| it "must return an empty array if it is given an empty array as an input" do | |
| empty_array = [] | |
| expect(flatten(empty_array)).to eq([]) | |
| end | |
| it "must flatten an array of nested integers" do | |
| array = [1,2,[3,[4,5]],[6,[7]],[8,9,10]] | |
| expect(flatten(array)).to eq([1,2,3,4,5,6,7,8,9,10]) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment