Created
November 18, 2015 22:09
-
-
Save jamesmartin/58310aaf5c3747598726 to your computer and use it in GitHub Desktop.
A tail-recursive flatten function, apparently (found code)
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
| exports.first = function(l) { | |
| return l[0] | |
| }; | |
| exports.rest = function(l) { | |
| return l.reduce(function(accumulator, item, index) { | |
| if(index > 0) { | |
| accumulator.push(item); | |
| } | |
| return accumulator; | |
| }, []); | |
| }; | |
| exports.flatten = function(l, accumulator){ | |
| if(l.length == 0) { | |
| return accumulator; | |
| } else { | |
| var head = exports.first(l); | |
| if(Array.isArray(head)) { | |
| return exports.flatten(head, accumulator); | |
| } else { | |
| accumulator.push(head); | |
| return exports.flatten(exports.rest(l), accumulator); | |
| } | |
| } | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found code from April 2015. I must have been thinking about functional programming. Quite probably written on a plane.