Created
June 21, 2019 21:03
-
-
Save newbenhd/7b1c95404cac21172cdcb4b483047245 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
/** | |
* returns a javascript object from a JSON formatted string | |
* Example json to javascript object: | |
* "5" -> 5 | |
* "'hello'" -> 'hello' | |
* "[]" -> [] | |
* "{}" -> {} | |
* "["hello"]" -> ['hello'] | |
* | |
* For more examples, use the JSON.stringify method in the console | |
*/ | |
function JSONParser(string) { | |
const tests = [isStringNumber, isStringString, isStringBoolean, isStringNull, isStringArray]; | |
const methods = [turnStringNumberToNumber, turnStringStringToString, turnStringBooleanToBoolean, turnStringNullToNull, turnStringArrayToArray]; | |
// console.log(string); | |
// check if it's number | |
if(tests[0](string)) return methods[0](string); | |
// check if it's string | |
if(tests[1](string)) return methods[1](string); | |
// check if it's boolean | |
// DON'T USE Boolean Object!! It returns true for any string. | |
if(tests[2](string)) return methods[2](string); | |
// check if string is null | |
if(tests[3](string)) return methods[3](string); | |
// check if string is array | |
if(tests[4](string)) return methods[4](string); | |
} | |
const whichTest = (arrayOfTests, value) => { | |
for(let i = 0; i < arrayOfTests.length; i++){ | |
if(arrayOfTests[i](value)){ | |
return i; | |
} | |
} | |
return -1; | |
} | |
const isStringNumber = (string) => { | |
return !isNaN(string); | |
} | |
const isStringString = (string) => { | |
return string.charAt(0) === '"' && string.charAt(string.length-1) === '"'; | |
} | |
const isStringBoolean = (string) => { | |
return string === "true" || string === "false"; | |
} | |
const isStringNull = (string) => { | |
return string === "null"; | |
} | |
const isStringArray = (string) => { | |
return string.charAt(0) === '[' && string.charAt(string.length-1) === ']'; | |
} | |
const turnStringNumberToNumber = (string) => { | |
return parseInt(string); | |
} | |
const turnStringStringToString = (string) => { | |
return string.substring(1, string.length - 1); | |
} | |
const turnStringBooleanToBoolean = (string) => { | |
return string === "true" ? true : false; | |
} | |
const turnStringNullToNull = (string) => { | |
return null; | |
} | |
const turnStringArrayToArray = (string, tests, methods) => { | |
// "["a"]" -> ["a"] | |
// "[true]" -> [true] | |
// "[1]" -> [1] | |
// "[false,1,"34"]" -> [false, 1, "34"] | |
// "[true,403485,"test"]" -> [true,403485,"test"] | |
const parsedString = string.substring(1, string.length - 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment