Skip to content

Instantly share code, notes, and snippets.

View edwinmeyer's full-sized avatar

Edwin Meyer edwinmeyer

View GitHub Profile
@edwinmeyer
edwinmeyer / flatten_array.rb
Last active January 17, 2018 00:31
Recursively flatten an array by flattening each half of the input array and concatenating the results.
module ArrayTransform
# Recursively flatten an array by flattening each half of the input array and concatenating the results.
# Special cases:
# 1) A zero-length array is returned unchanged
# 2) An array nested inside a single-element array is flattened and returned.
# Terminating condition: An array containing a single non-array-element is returned without modification
def self.flatten(obj)
raise "flatten: Array required; #{obj.class} provided" unless obj.is_a?(Array)
olen = obj.length # because we use it multiple times