Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function findDepth(item) {
- if (Array.isArray(item) == false) return 0;
- if (item.length == 0) return 1;
- return 1 + findDepth(item[0]);
- }
- function depthToBracket(d) {
- let ret = "";
- for (let i = 1; i <= d; i++) {
- ret += "[]";
- }
- return ret;
- }
- function doFlat(item, depth, type) {
- if (depth == 0) return item;
- if (item.length === 0) return `new ${type}[]{}`;
- return `new ${type}${depthToBracket(depth)}{${item.map(i => doFlat(i, depth - 1, type))}}`;
- }
- function flatter(item, type = "int") {
- const depth = findDepth(item);
- return `${doFlat(item, depth, type)};`;
- }
- console.log(flatter([1, 2]));
- console.log(flatter([]));
- console.log(flatter([[1, 2], [3, 4]]));
- console.log(flatter([[[], []], [[], []]]));
- console.log(flatter([[[], []], [[1], []]]));
Advertisement
Add Comment
Please, Sign In to add comment