Skip to content

Instantly share code, notes, and snippets.

@juanfurattini
Last active July 26, 2018 06:22
Show Gist options
  • Save juanfurattini/a8d3a7069830aa3106739717a2b55fa3 to your computer and use it in GitHub Desktop.
Save juanfurattini/a8d3a7069830aa3106739717a2b55fa3 to your computer and use it in GitHub Desktop.
Flattens an Array without using the built-in Array#flatten method (For testing it requires spec)
module ArrayUtils
extend self
# Converts a nested array to a flatten array without using the built-in method Array#flatten
# It doesn't remove nil
#
# If the passed parameter is not an array, the same object is returned
# to_flat_array(nil) #=> nil
# to_flat_array({ a: 'something }) #=> {:a=>"something"}
# If the passed parameter is a nested array, a flatten array is returned
# to_flat_array([[1, 2, [3]], 4]) #=> [1, 2, 3, 4]
# If the passed parameter is an array, and contains a non array element inside, that element is not changed
# to_flat_array([1, 2, 3, 4, { a: 'a' }]) #=> [1, 2, 3, 4, {:a=>"a"}]
def to_flat_array(array = [])
# If the passed object is not an array, the same object must be returned
return array unless array.is_a?(Array)
array.inject([]) do |result, element|
result.push *(element.is_a?(Array) ? to_flat_array(element) : [element])
end
end
end
require_relative 'array_flattener.rb'
require 'rspec'
RSpec.describe ArrayUtils do
context '::to_flat_array' do
context 'when an array is passed' do
context 'and it has nested arrays inside' do
it 'must return a unique flatten array' do
expect(ArrayUtils::to_flat_array([[1, 2, [3]], 4])).to eq([1, 2, 3, 4])
end
end
context 'and it has no nested arrays inside' do
it 'must return the same array' do
expect(ArrayUtils::to_flat_array([1, 2, 3, 4])).to eq([1, 2, 3, 4])
end
end
end
context 'when a non-array is passed' do
it 'must return the same object' do
expect(ArrayUtils::to_flat_array({ a: 'something' })).to eq({ a: 'something' })
end
end
context 'when nil is passed' do
it 'must return nil' do
expect(ArrayUtils::to_flat_array(nil)).to be_nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment