Skip to content

Instantly share code, notes, and snippets.

@sillyfellow
Created March 28, 2020 22:30
Show Gist options
  • Save sillyfellow/8eb7d7e19172adb725b5f60d3a8154ae to your computer and use it in GitHub Desktop.
Save sillyfellow/8eb7d7e19172adb725b5f60d3a8154ae to your computer and use it in GitHub Desktop.
function flatten(arr) {
if (arr.length == 0) {
return [];
}
const first = arr[0];
const flatRest = flatten(arr.slice(1));
if (!Array.isArray(first)) {
return [first].concat(flatRest);
}
return flatten(first).concat(flatRest);
}
const tests = [
[],
[1],
[1, 2],
[1, 2, [3]],
[1, 2, [3], [4, [5, [6]]]],
[[[1], 2, 3], 4, 5, [[[6, 7], 8]]],
];
tests.forEach(arr => {
console.log(arr, " --> ", flatten(arr));
});
function sReverse(s) {
if (s.length < 2) {
return s;
}
return sReverse(s.substring(1)) + s[0];
}
["", "1", "12", "123"].forEach(s => {
console.log(s, " --> ", sReverse(s));
});
@sillyfellow
Copy link
Author

flatten a list (recursively)
reverse a string (recursively)

in javascript

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