Skip to content

Instantly share code, notes, and snippets.

@joshuatf
Created May 24, 2018 13:48
Show Gist options
  • Save joshuatf/7011eb7bb509e5d7878df30063d4100b to your computer and use it in GitHub Desktop.
Save joshuatf/7011eb7bb509e5d7878df30063d4100b to your computer and use it in GitHub Desktop.
ArrayUtils - Array flattener
require 'rspec'
# Utils for flattening an array recursively
# Usage: ArrayUtils.new(array_to_flatten).flatten
class ArrayUtils
def initialize(array)
raise 'Must be initialized with an array' unless array.kind_of? Array
@array = array
end
def flatten
recursive_flatten(@array, [])
end
private
def recursive_flatten(array, flattened)
array.each do |item|
if item.kind_of? Array
recursive_flatten(item, flattened)
else
flattened << item
end
end
flattened
end
end
# RSpec tests
RSpec.describe ArrayUtils do
it 'flattens [1, 2, 3, 4]' do
expect(ArrayUtils.new([1, 2, 3, 4]).flatten).to eq [1, 2, 3, 4]
end
it 'flattens [1, [2], 3, 4]' do
expect(ArrayUtils.new([1, [2], 3, 4]).flatten).to eq [1, 2, 3, 4]
end
it 'flattens [1, [2, 3], 4]' do
expect(ArrayUtils.new([1, [2, 3], 4]).flatten).to eq [1, 2, 3, 4]
end
it 'flattens [1, [2, 3], 4]' do
expect(ArrayUtils.new([1, [2, 3], 4]).flatten).to eq [1, 2, 3, 4]
end
it 'flattens [[1, [2, [3]], 4]]' do
expect(ArrayUtils.new([[1, [2, [3]], 4]]).flatten).to eq [1, 2, 3, 4]
end
it 'flattens [[[1, [2, 3], 4]]]' do
expect(ArrayUtils.new([[[1, [2, 3], 4]]]).flatten).to eq [1, 2, 3, 4]
end
it 'checks if array' do
expect {
ArrayUtils.new('1, 2, 3, 4')
}.to raise_error('Must be initialized with an array')
end
it 'checks if not nil' do
expect {
ArrayUtils.new('')
}.to raise_error('Must be initialized with an array')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment