Created
July 1, 2018 18:48
-
-
Save betasve/794a7d6c572b149b983b198ed245fdfa to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# A simple Ruby class providing an alternative implementation | |
# of the *Array#flatten method* | |
# | |
# Author:: Svetoslav Blyahov | |
class Flattener | |
# The initializer method needed for the alternative flatten prcedure | |
# | |
# @param [Array] arr | |
def initialize(arr) | |
@arr = arr | |
end | |
# The alternative to Array#flatten method | |
# that's performing flattening to arrays provided to this class' initializer | |
# | |
# @return [Array] | |
def flatten | |
return [] if @arr.nil? | |
@flattened ||= [] | |
@arr.map do |e| | |
@flattened.push(e) && next if e.nil? || Array(e) != e | |
@flattened += self.class.new(e).flatten | |
end | |
@flattened | |
end | |
end |
This file contains hidden or 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 'rspec' | |
require_relative 'flattener.rb' | |
describe Flattener do | |
describe '#flatten' do | |
subject { Flattener.new(preset).flatten } | |
let(:flatted_array) { preset.to_a.flatten } | |
context 'when empty array' do | |
let(:preset) { [] } | |
it { is_expected.to eq flatted_array } | |
end | |
context 'when `nil` passed' do | |
let(:preset) { nil } | |
it { is_expected.to eq flatted_array } | |
end | |
context 'when already a flat array' do | |
let(:preset) { [1, 2, 3, 4] } | |
it { is_expected.to eq flatted_array } | |
end | |
context 'when a "flattable" array' do | |
context 'and the array is heterogeneous' do | |
let(:preset) { [1, 2, 3, [4, 5, [8, 7]]]} | |
it { is_expected.to eq flatted_array } | |
end | |
context 'and the array is homogeneous' do | |
let(:preset) { [[1, 2], [3], [4, 5], [8, 7, 9]]} | |
it { is_expected.to eq flatted_array } | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment