Skip to content

Instantly share code, notes, and snippets.

@lemieszek
Last active October 13, 2020 06:09
Show Gist options
  • Save lemieszek/15cbaa069be907967d809f3846288dd8 to your computer and use it in GitHub Desktop.
Save lemieszek/15cbaa069be907967d809f3846288dd8 to your computer and use it in GitHub Desktop.
Cassidoo 2020.10.12
/*
Given a basic Lisp-like string expression, parse it,
where the available functions are
add, subtract, multiply, and divide,
and they all take in 2 values.
Examples:
babyLisp('(add 1 2)')
3
babyLisp('(multiply 4 (add 2 3))')
20
babyLisp('(multiply (add 2 (multiply 3 5)) 4)')
68
*/
const babyLisp = (str) => {
const functions = {
add: (a, b) => babyLisp(a) + babyLisp(b),
subtract: (a, b) => babyLisp(a) - babyLisp(b),
multiply: (a, b) => babyLisp(a) * babyLisp(b),
divide: (a, b) => babyLisp(a) / babyLisp(b),
};
let body = `${str}`;
if (body[0] === '(' && body[body.length - 1] === ')') {
body = body.slice(1, -1);
}
const [first, ...rest] = body.split(' ');
if (!isNaN(Number(first)) && rest.length === 0) {
// Ladies and gentlemen, we got it //
return Number(first);
}
const args = [];
let index = 0;
let parenthesisDepth = 0; // We will deal with depth with recursion
for (const v of body.slice(first.length + 1)) {
if (v === '(') parenthesisDepth++;
if (v === ')') parenthesisDepth--;
if (v === ' ' && parenthesisDepth === 0) {
index++;
} else {
args[index] = (args[index] || '') + v;
}
}
return functions[first](...args);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment