Created
February 25, 2018 13:33
-
-
Save Skillvendor/9ac6b5e139c1d9775b51bcd757dec779 to your computer and use it in GitHub Desktop.
Ruby Array Flattener
This file contains 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 'rspec' | |
# class used to flatten arrays | |
# Input: | |
# @param [Array] arr: the array that needs flattening | |
# Output when flatten method is invoked: | |
# @param [Array] flattened array | |
class Flattener | |
def initialize(arr) | |
raise 'Pass an array' unless arr.kind_of? Array | |
@arr = arr | |
end | |
def flatten | |
get_flattened_array @arr | |
end | |
private | |
def get_flattened_array arr | |
arr.reduce([]) do |result, item| | |
if item.is_a? Array | |
result + get_flattened_array(item) | |
else | |
result << item | |
end | |
end | |
end | |
end |
This file contains 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 './spec_helper' | |
require './flattener' | |
RSpec.describe Flattener do | |
context 'valid input' do | |
TEST_CASES = [ | |
[1, 2, 3], | |
[], | |
[1, 2, 3, [1, 2, 3]], | |
[1, [1], [[1]], [[2], [3]]] | |
] | |
TEST_CASES.each do |test_case| | |
#context needed otherwise it can retain values from other context and we get random failures | |
context "#{test_case}" do | |
subject { Flattener.new(test_case) } | |
it "returns the right result for #{test_case}" do | |
expect(subject.flatten).to eq(test_case.flatten) | |
end | |
end | |
end | |
end | |
context 'invalid input' do | |
subject { Flattener.new('something') } | |
it 'checks if array was passed' do | |
expect { | |
subject.flatten | |
}.to raise_error('Pass an array') | |
end | |
end | |
end |
This file contains 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
source 'https://rubygems.org' | |
gem 'rspec', '~> 3.4' |
This file contains 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 'rspec' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment