Created
August 19, 2019 05:06
-
-
Save wilbert/e1818815028d6db4a0dcd24bc209bb86 to your computer and use it in GitHub Desktop.
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
# == Flattenator | |
# | |
# Author: Wilbert Ribeiro | |
# | |
# Ruby is an object-oriented language, that can support other paradigms like | |
# functional style of programming. | |
# | |
# Flattenator class provides an improved way to flatten ruby arrays with any | |
# dimension, using functional style to increase performance. | |
# | |
# A minimal implementation could be: | |
# | |
# => Flattenator.flatten!([1,2,3,[4,5,[6,7,[8]]],9,10]) | |
# => [1,2,3,4,5,6,7,8,9,10] | |
require 'rubygems' | |
require 'rspec' | |
class Flattenator | |
class << self | |
def flatten!(array) | |
return nil unless array.is_a?(Array) | |
array.reduce([]){|a,b| b.is_a?(Array) ? a.concat(flatten!(b)) : a << b } | |
end | |
end | |
end | |
describe Flattenator do | |
let(:array) { [1,2,3,[4,5,[6,7,[8]]],9,10] } | |
it 'should flatten array' do | |
expect(Flattenator.flatten!(array)).to eq([1,2,3,4,5,6,7,8,9,10]) | |
end | |
it 'should return nil if array is nil' do | |
expect(Flattenator.flatten!(nil)).to eq(nil) | |
end | |
it 'should return nil if param is not array' do | |
expect(Flattenator.flatten!(1)).to eq(nil) | |
end | |
it 'should return empty array' do | |
expect(Flattenator.flatten!([])).to eq([]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment