Skip to content

Instantly share code, notes, and snippets.

@betesh
Last active January 8, 2020 04:01
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 betesh/98d8ed01ead82ad9f19e6cc82190b7c1 to your computer and use it in GitHub Desktop.
Save betesh/98d8ed01ead82ad9f19e6cc82190b7c1 to your computer and use it in GitHub Desktop.
Flattening
Gemfile.lock
examples.txt
require:
- rubocop-performance
- rubocop-rspec
AllCops:
DisplayCopNames: true
DisplayStyleGuide: true
EnabledByDefault: true
ExtraDetails: true
TargetRubyVersion: 2.6
# Override defaults where I have different preferences:
Metrics/BlockLength:
Max: 40
RSpec/ExpectChange:
EnforcedStyle: block
# Disable the cops that don't add value in this project in my opinion.
# As stated, this is *my* opinion. *Your* opinion will probably be different
# but that's ok. If this were a team project, we could still use rubocop for
# the cops that we agree on.
Bundler/GemComment:
Enabled: false
Style/Copyright:
Enabled: false
Style/MissingElse:
Enabled: false

Array#as_flat_array

A Ruby implementation of flattening an Array

The specification

  • The code should 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].
  • The code must be well tested and documented.
  • Include unit tests and any documentation you feel is necessary.
  • Avoid using language defined methods like Ruby's Array#flatten or JavaScript's Array.flat.

Assumptions

The specification calls for dealing with Arrays that only contain integers. It leaves unclear how the implementation should handle non-integer values. Possibilites include raising an Exception, printing a warning, leaving them out of the resulting Array, or including them in the resulting Array without putting up a fuss. I chose the last approach because all of the other approaches seemed foolish:

  • With few exceptions, raising exceptions should only be used for situations that the code cannot handle, and we can handle this situation.
  • Printing a warning makes sense when the code is able to detect a situation that is likely to be a bug or require user attention, but there is no reason to assume that non-integer values indicate that the user did something unintentional or introduced a bug
  • Dropping elements violates the Principle of least astonishment

I theorize that the specification refers specifically to integers to ease the development process in typed languages, but I chose to use Ruby, where Arrays containing Integers can always contain non-Integers as well, so this narrow requirement didn't save me any effort with regards to non-Integer objects. I therefore chose to handle not only all non-integer Objects, but even non-Objects (i.e. BasicObjects).

Testing

The code in this gist is tested using RSpec. To run tests:

$ bundle exec rspec array_spec.rb

Developing

After cloning the gist, install the bundled gems:

$ bundle

Before comitting code, ensure it follow the rubocop configuration:

$ bundle exec rubocop
# frozen_string_literal: true
require_relative('basic_object')
# Re-opened Array class to define new methods
class Array
# Return a flat version of this Array. This method will always return a flat,
# unfrozen, new Array.
def as_flat_array
new_array = []
each do |element|
new_array.concat(element.as_flat_array)
end
new_array
end
end
# frozen_string_literal: true
require_relative('spec_helper')
require_relative('array')
RSpec.describe(Array) do
describe '#as_flat_array' do
shared_examples 'returns a new flat Array' do |expected_new_array|
before do
# Freezing the Array ensures calls to 'as_flat_array' don't modify the
# original Array
array.freeze
end
it 'returns a new flat Array' do
expect(array.as_flat_array).to(eq(expected_new_array))
end
it 'returns an unfrozen flat Array' do
expect(array.as_flat_array).not_to(be_frozen)
end
end
context 'when the Array is already flat' do
let(:array) { [1, 2, 3] }
it_behaves_like 'returns a new flat Array', [1, 2, 3]
# Returning the original Array would be a performance optimization
# and I strongly considered taking that route. However, it comes at
# a price: A user who doesn't know the Array is already flat may assume
# that this returns a new Array that is safe to modify when the original
# is either frozen or is unsafe to modify. Since we're using recursion,
# this could cause nested Arrays to return themselves, making this even
# more confusing, i.e. [1,2,[3,4]].as_flat_array would return a new Array
# containing the original [3,4] Array. For this reason, I decided that
# it's safer to guarantee that a new Array is always returned instead of
# assuming that the user will remember to check.
it 'does not return the original Array' do
expect(array.as_flat_array).not_to(equal(array))
end
end
context 'when the Array has one layer of nesting' do
let(:array) { [1, 2, [3, 4]] }
it_behaves_like 'returns a new flat Array', [1, 2, 3, 4]
end
context 'when the Array has numerous layers of nesting' do
let(:array) { [1, 2, [3, 4, [:sym1, nil], [[[99]]]]] }
it_behaves_like 'returns a new flat Array', [1, 2, 3, 4, :sym1, nil, 99]
end
context 'when the Array contains an element that is not an Object' do
not_an_object = BasicObject.new
let(:array) { [1, 2, [3, not_an_object]] }
it_behaves_like 'returns a new flat Array', [1, 2, 3, not_an_object]
end
end
end
# frozen_string_literal: true
# Re-opened BasicObject class to define new methods
class BasicObject
# Method that returns the same Object, wrapped in an Array.
# The purpose of this method is so that Array#as_flat_array
# can avoid type-checking and instead be certain that all
# objects respond to #as_flat_array with a value that can
# be concatenated to an already flat Array in a way that
# ensures that it remains flat.
def as_flat_array
[self]
end
end
# frozen_string_literal: true
source('https://rubygems.org')
# For testing my code
gem('rspec')
# For a strict coding style
gem('rubocop')
gem('rubocop-performance')
gem('rubocop-rspec')
# frozen_string_literal: true
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with(:rspec) do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with(:rspec) do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching(:focus)
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = 'examples.txt'
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand(config.seed)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment