This Gist was automatically created by Carbide, a free online programming environment.
Created
November 12, 2016 18:44
-
-
Save sliminality/2220d4d533814020c3891569285518fd to your computer and use it in GitHub Desktop.
Parsing
This file contains hidden or 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
const jsonString = '{ name: Bob, children: { son: { name: MiniBob }, daughter: { name: Clara } }, age: fourteen }'; | |
// function stringToJSON (str) { | |
// const pairs = []; | |
// for (const c in str) { | |
// if (c === '{') { | |
// // When you see a {, start a new array of pairs | |
// } | |
// } | |
// } | |
function leafString (str) { | |
const pairs = []; | |
let currentToken = ''; | |
let currentKey = ''; | |
for (const c of str.substring(1)) { | |
// If it's a colon, save the current token as a key | |
if (c === ':') { | |
currentKey = currentToken; | |
currentToken = ''; | |
} | |
// If it's the end of a key, save the current (key, token) pair | |
else if (c === ',' || c === '}') { | |
pairs.push([ currentKey, currentToken ]); | |
currentKey = ''; | |
currentToken = ''; | |
} | |
else { | |
currentToken += c; | |
} | |
} | |
return pairs; | |
} | |
leafString('{ a: apple, b: boy, c: cat }'); | |
// stringToJSON(jsonString); |
This file contains hidden or 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
///http://eloquentjavascript.net/11_language.html | |
function bracketParser (str) { | |
const stack = []; | |
const tokens = []; | |
const results = []; | |
let currentToken = ''; | |
for (const c of str) { | |
if (c === '[') { | |
stack.push(c); | |
tokens.push(currentToken); | |
currentToken = ''; | |
} else if (c === ']') { | |
const left = stack.pop(); | |
if (currentToken.length) { | |
results.push(currentToken); | |
} | |
currentToken = tokens.pop(); | |
} else { | |
currentToken += c; | |
} | |
} | |
return results; | |
} | |
bracketParser('[xxx[y[zzz]y]x]'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment