Last active
February 2, 2017 18:18
-
-
Save HarlemSquirrel/28c4ebcb242d010fef5d9ddb26199586 to your computer and use it in GitHub Desktop.
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
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 |
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_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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check out the benchmarking for this as well.