Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created November 18, 2015 22:09
Show Gist options
  • Select an option

  • Save jamesmartin/58310aaf5c3747598726 to your computer and use it in GitHub Desktop.

Select an option

Save jamesmartin/58310aaf5c3747598726 to your computer and use it in GitHub Desktop.
A tail-recursive flatten function, apparently (found code)
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);
}
}
};
@jamesmartin

Copy link
Copy Markdown
Author

Found code from April 2015. I must have been thinking about functional programming. Quite probably written on a plane.

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