Implementation
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
#!/usr/bin/env ruby | |
class Flatten | |
def self.flatten(array) | |
result = [] | |
array.each do |x| | |
if x.kind_of? Array # flatten again and add the elements individually | |
self.flatten(x).each { |y| result.push(y) } | |
else | |
result.push(x) #add the item to the result array | |
end | |
end | |
return result | |
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 'minitest/autorun' | |
require 'minitest/spec' | |
require './flatten' | |
#place this file on the same folder as flatten.rb and run rake test to run these tests | |
describe Flatten do | |
before (:each) do | |
@cases = [ [1,2,3,4,5], [3,4,6,[3,4] ], [4,[3,4],[2,[1]]],[1,[3,4,[5,6],7,9 ],10] ] | |
end | |
it "returns an array" do | |
@cases.each { |x| Flatten.flatten(x).must_be_instance_of(Array) } | |
end | |
it "returns a non empty array for non empty entries" do | |
@cases.each { |x| Flatten.flatten(x).wont_be_empty } | |
end | |
it "returns an empty array when given empty entry" do | |
Flatten.flatten([]).must_be_empty | |
end | |
it "returns a non nested array" do | |
@cases.each do |x| | |
Flatten.flatten(x).each do |y| | |
y.wont_be_instance_of(Array) | |
end | |
end | |
end | |
it "has the same amount of elements than an array flattened with native method" do | |
@cases.each do |x| | |
Flatten.flatten(x).length.must_equal x.flatten.length | |
end | |
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
source 'https://rubygems.org/' | |
gem 'minitest' |
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 'rake/testtask' | |
Rake::TestTask.new do |t| | |
t.libs << "spec" | |
t.pattern = "*_spec.rb" | |
t.verbose = true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment