Created
April 19, 2021 17:23
-
-
Save jjori-master/2d0418bf26a18d3fa332bf12a04819ac to your computer and use it in GitHub Desktop.
This file contains 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
if (1) { | |
// 꼬리재귀.. | |
const stringCheck = [ | |
[/[\r\n\l]/g, "\\n"], | |
[/"/g, '\\"', [/\t/g, "\\t"]], | |
]; | |
const el = { | |
number: (v) => v.toString(), | |
boolean: (v) => v.toString(), | |
string: (v, isObjectValue) => { | |
for (let i = 0; i < stringCheck.length; i++) { | |
v = v.replace(stringCheck[0], stringCheck[1]); | |
} | |
if (isObjectValue) { | |
v = `\"${v}\"`; | |
} | |
return v; | |
}, | |
stringify(v, isObjectValue) { | |
return this[typeof v]?.(v, isObjectValue) ?? "null"; | |
}, | |
}; | |
const arrToString = (arr) => { | |
let str = ""; | |
for (const v of arr) str += `,${v}`; | |
return `[${str.substr(1)}]`; | |
}; | |
const objectToString = (arr) => { | |
let str = ""; | |
for (const objElement of arr) | |
str += `,\"${objElement[0]}\":${el.stringify(objElement[1], true)}`; | |
return `{${str.substr(1)}}`; | |
}; | |
const recursive = (arr, acc, i, isObject, stack) => { | |
if (i < arr.length) { | |
switch (true) { | |
case arr[i].constructor == ({}).constructor: | |
stack.push([arr, acc, i + 1, false]); | |
return recursive(Object.entries(arr[i]), [], 0, true, stack); | |
case Array.isArray(arr[i]): | |
if (isObject) { | |
acc.push(arr[i]); | |
return recursive(arr, acc, i + 1, isObject, stack); | |
} else { | |
stack.push([arr, acc, i + 1, false]); | |
return recursive(arr[i], [], 0, false, stack); | |
} | |
default: | |
acc.push(el.stringify(arr[i])); | |
return recursive(arr, acc, i + 1, isObject, stack); | |
} | |
} else { | |
let accStr = ""; | |
if (isObject) { | |
accStr = objectToString(acc); | |
} else { | |
accStr = arrToString(acc); | |
} | |
const pre = stack.pop(); | |
if (pre) { | |
const [prevArr, prevAcc, prevIndex, isObject] = pre; | |
prevAcc.push(accStr); | |
recursive(prevArr, prevAcc, prevIndex, isObject, stack); | |
} else { | |
return accStr; | |
} | |
} | |
}; | |
const stringify = (arr) => { | |
if (!Array.isArray(arr)) throw "Invalid arr"; | |
return recursive(arr, [], 0, false, []); | |
}; | |
stringify([1,2,{ name: "jjoir", age: 38 },[4, 5, 6],{ name: "good", age: 12, isObject: true },]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
74번째줄이 잘못되었는데 정상작동함?