Skip to content

Instantly share code, notes, and snippets.

@HarlemSquirrel
Last active February 2, 2017 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarlemSquirrel/28c4ebcb242d010fef5d9ddb26199586 to your computer and use it in GitHub Desktop.
Save HarlemSquirrel/28c4ebcb242d010fef5d9ddb26199586 to your computer and use it in GitHub Desktop.
Flattener
class Flattener
def initialize(nested_array)
@nested_array = nested_array
end
def call
@flattened_array = []
flatten(nested_array)
flattened_array
end
private
attr_reader :flattened_array, :nested_array
def flatten(array)
array.each { |i| i.is_a?(Array) ? flatten(i) : flattened_array << i }
end
end
require_relative 'flattener'
RSpec.describe Flattener do
let(:flattener) { described_class.new nested_array }
describe '#call' do
context "with a small nested array" do
let(:flattened_array) { [1,2,3,4] }
let(:nested_array) { [[1,2,[3]],4] }
it 'flattens nested arrays' do
expect(flattener.call).to eq flattened_array
end
end
context "with a large nested array" do
let(:flattened_array) { %w(a b c d e f g) }
let(:nested_array) { ["a", ["b", "c", ["d", [[["e"]]]]], "f", [["g"]]] }
it 'flattens nested arrays' do
expect(flattener.call).to eq flattened_array
end
end
end
end
@HarlemSquirrel
Copy link
Author

Check out the benchmarking for this as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment