Last active
May 28, 2019 17:25
-
-
Save coolsoftwaretyler/0b2e8a5fc41f77ff0ad9221662ff1f2c to your computer and use it in GitHub Desktop.
An array flatten method written in Ruby for Theorem LLC interview. Uses RSpec for unit tests. Created by Tyler Williams. [email protected]
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
| # Use RSpec for testing https://rspec.info/ | |
| require 'rspec' | |
| # Define the flatten function, we'll use it recursively | |
| # On the initial run, set `results` to an empty array | |
| def flatten(array, results = []) | |
| # Check that array is not nil | |
| if array | |
| # For each item in the array, check if it's a nested array | |
| array.each do |item| | |
| # If the item is an array, run `flatten()` on it, and pass in the results array as well | |
| if item.class == Array | |
| flatten(item, results) | |
| else | |
| # If the item isn't an array, toss it in the results array | |
| results << item | |
| end | |
| end | |
| # Return the results array | |
| results | |
| else | |
| # Return a message asking user to provide an array | |
| 'Please provide an array' | |
| end | |
| end | |
| # Unit tests with RSpec | |
| # Be sure to run `gem install rspec` and `rspec flatten.rb` in the directory | |
| describe 'Flatten' do | |
| it 'asks user for an array when provided nil' do | |
| expect(flatten(nil)).to eq('Please provide an array') | |
| end | |
| it 'handles an empty array' do | |
| expect(flatten([])).to eq([]) | |
| end | |
| it 'handles a flat array' do | |
| expect(flatten([1,2,3])).to eq([1,2,3]) | |
| end | |
| it 'handles a nested array' do | |
| expect(flatten([[1,2,[3]],4])).to eq([1,2,3,4]) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment