Last active
July 10, 2018 17:55
-
-
Save veezus/8d2fd40e18106acba5fe7a4dc36e31d0 to your computer and use it in GitHub Desktop.
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
# Write some code, that will flatten an array of arbitrarily nested arrays of | |
# integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
# Your solution should be a link to a gist on gist.github.com with your | |
# implementation. | |
# When writing this code, you can use any language you're comfortable with. The | |
# code must be well tested and documented if necessary, and in general please | |
# treat the quality of the code as if it was ready to ship to production. | |
# Try to avoid using language defined methods like Ruby's Array#flatten. | |
class Flatten | |
attr_reader :values | |
# Preserve .initialize for dependency injection | |
def call input | |
@values = input.dup | |
output = [] | |
values.map do |value| | |
if value.is_a? Array | |
output += Flatten.new.call(value) | |
else | |
output << value | |
end | |
end | |
output | |
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 'rspec' | |
require './flatten' | |
describe Flatten do | |
describe "#call" do | |
it "returns the passed-in array if there are no sub-arrays" do | |
expect(Flatten.new.call([1, 2])).to eq [1, 2] | |
end | |
context "when there are sub-arrays" do | |
it "returns the flattened array" do | |
expect(Flatten.new.call([1, [2]])).to eq [1, 2] | |
expect(Flatten.new.call([1, [2], 3, [3, 2, [4, 5], 6]])).to \ | |
eq [1, 2, 3, 3, 2, 4, 5, 6] | |
end | |
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
# frozen_string_literal: true | |
ruby '2.5.1' | |
source "https://rubygems.org" | |
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } | |
gem "rspec" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment