Skip to content

Instantly share code, notes, and snippets.

@adimasuhid
Last active July 4, 2017 05:25
Show Gist options
  • Save adimasuhid/2d01342c435133fe1dd3ebc86626cf15 to your computer and use it in GitHub Desktop.
Save adimasuhid/2d01342c435133fe1dd3ebc86626cf15 to your computer and use it in GitHub Desktop.
Module to Flatten Arrays
#
# flattener.rb
#
module Flattener
class ::InvalidInputError < StandardError; end
def self.execute(array)
raise InvalidInputError unless can_be_flattened?(array)
process(array)
end
private
def self.can_be_flattened?(object)
object.is_a? Array
end
def self.process(array)
sum = []
array.each do |obj|
sum += can_be_flattened?(obj) ? process(obj) : [obj]
end
sum
end
end
#
# flattener_spec.rb
#
require_relative 'flattener.rb'
RSpec.describe Flattener do
describe ".execute" do
context "given an array" do
it "returns empty array from empty array" do
expect(subject.execute([])).to eq []
end
it "returns the same array given a one level array" do
flat_array = [1,2,3]
expect(subject.execute(flat_array)).to eq flat_array
end
it "returns a flat array given a multi level array" do
leveled_array = [1, [2], [3,4,[5]]]
expect(subject.execute(leveled_array)).to eq [1,2,3,4,5]
end
it "returns a flat array given non-integer contents" do
leveled_array = [{}, ["A"], [3,4,[5], [6,[7]]]]
expect(subject.execute(leveled_array)).to eq [{},"A",3,4,5,6,7]
end
end
context "given a non-array" do
it "returns InvalidInputError" do
expect{ subject.execute({}) }.to raise_error InvalidInputError
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment