Skip to content

Instantly share code, notes, and snippets.

@veezus
Last active July 10, 2018 17:55
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 veezus/8d2fd40e18106acba5fe7a4dc36e31d0 to your computer and use it in GitHub Desktop.
Save veezus/8d2fd40e18106acba5fe7a4dc36e31d0 to your computer and use it in GitHub Desktop.
# 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
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
# 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