Skip to content

Instantly share code, notes, and snippets.

@sliminality
Created November 12, 2016 18:44
Show Gist options
  • Save sliminality/2220d4d533814020c3891569285518fd to your computer and use it in GitHub Desktop.
Save sliminality/2220d4d533814020c3891569285518fd to your computer and use it in GitHub Desktop.
Parsing
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);
///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