Created
August 30, 2011 06:28
-
-
Save lambdalisue/1180321 to your computer and use it in GitHub Desktop.
flatten (convert multidimensional array to one dimensinal array) function written in CoffeeScript
This file contains 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
#!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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Didn't work for IE8 for me.