3.3 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	
			3.3 KiB
		
	
	
	
	
	
	
	
title, id, challengeType, forumTopicId
| title | id | challengeType | forumTopicId | 
|---|---|---|---|
| S-Expressions | 59667989bf71cf555dd5d2ff | 5 | 302303 | 
Description
Instructions
((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))and turn it into a native data structure. (See the Pike, Python and Ruby implementations for examples of native data structures.)
Tests
tests:
  - text: <code>parseSexpr</code> is a function.
    testString: assert(typeof parseSexpr === 'function');
  - text: <code>parseSexpr('(data1 data2 data3)')</code> should return <code>['data1', 'data2', 'data3']</code>
    testString: assert.deepEqual(parseSexpr(simpleSExpr), simpleSolution);
  - text: <code>parseSexpr('(data1 data2 data3)')</code> should return an array with 3 elements.
    testString: assert.deepEqual(parseSexpr(basicSExpr), basicSolution);
Challenge Seed
function parseSexpr(str) {
  // Good luck!
  return true;
}
After Test
const simpleSExpr = '(data1 data2 data3)';
const simpleSolution = ['data1', 'data2', 'data3'];
const basicSExpr = '((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))';
const basicSolution = [["data","\"quoted data\"",123,4.5],["data",["!@#",[4.5],"\"(more\"","\"data)\""]]];
Solution
function parseSexpr(str) {
  const t = str.match(/\s*("[^"]*"|\(|\)|"|[^\s()"]+)/g);
  for (var o, c = 0, i = t.length - 1; i >= 0; i--) {
    var n,
      ti = t[i].trim();
    if (ti == '"') return;
    else if (ti == '(') t[i] = '[', c += 1;
    else if (ti == ')') t[i] = ']', c -= 1;
    else if ((n = +ti) == ti) t[i] = n;
    else t[i] = `'${ti.replace('\'', '\\\'')}'`;
    if (i > 0 && ti != ']' && t[i - 1].trim() != '(') t.splice(i, 0, ',');
    if (!c) if (!o) o = true; else return;
  }
  return c ? undefined : eval(t.join(''));
}