Skip to content

Instantly share code, notes, and snippets.

@lambdalisue
Created August 30, 2011 06:28
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 lambdalisue/1180321 to your computer and use it in GitHub Desktop.
Save lambdalisue/1180321 to your computer and use it in GitHub Desktop.
flatten (convert multidimensional array to one dimensinal array) function written in CoffeeScript
#!coffee
#
# Convert multidimensional array to one dimensional array.
# Return an empty list when passed array is an empty list.
#
# Usage::
#
# assert = require 'assert'
# matrix = [
# [0, 1, 2];
# [3, 4, 5];
# [6, 7, 8]
# ]
# assert.deepEqual flatten(matrix), [0, 1, 2, 3, 4, 5, 6, 7, 8]
#
flatten = (a) ->
if a.length is 0 then return []
a.reduce (lhs, rhs) -> lhs.concat rhs
# --- unittest via 'assert' module of node.js
unittest = ->
assert = require 'assert'
matrix = [
[0, 1, 2];
[3, 4, 5];
[6, 7, 8]
]
assert.deepEqual flatten(matrix), [0, 1, 2, 3, 4, 5, 6, 7, 8]
unittest()
@jopotts
Copy link

jopotts commented Jan 31, 2012

Didn't work for IE8 for me.

@full-of-foo
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment