najimCseJu

JsArrayToJava

Apr 11th, 2019
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function findDepth(item) {
  2.     if (Array.isArray(item) == false) return 0;
  3.     if (item.length == 0) return 1;
  4.     return 1 + findDepth(item[0]);
  5. }
  6. function depthToBracket(d) {
  7.     let ret = "";
  8.     for (let i = 1; i <= d; i++) {
  9.         ret += "[]";
  10.     }
  11.     return ret;
  12. }
  13. function doFlat(item, depth, type) {
  14.     if (depth == 0) return item;
  15.     if (item.length === 0) return `new ${type}[]{}`;
  16.     return  `new ${type}${depthToBracket(depth)}{${item.map(i => doFlat(i, depth - 1, type))}}`;
  17. }
  18. function flatter(item, type = "int") {
  19.     const depth = findDepth(item);
  20.     return `${doFlat(item, depth, type)};`;
  21. }
  22.  
  23. console.log(flatter([1, 2]));
  24. console.log(flatter([]));
  25. console.log(flatter([[1, 2], [3, 4]]));
  26. console.log(flatter([[[], []], [[], []]]));
  27. console.log(flatter([[[], []], [[1], []]]));
Advertisement
Add Comment
Please, Sign In to add comment