fork download
  1.  
  2. /*
  3. PROBLEM: Evaluate a Nested Math Expression
  4. FOLLOW-UP 3: Handle Invalid Input
  5.  
  6. Valid functions:
  7.   add(x, y)
  8.   sub(x, y)
  9.   mul(x, y)
  10.   div(x, y)
  11.   pow(x, y)
  12.  
  13. Examples:
  14.   add(1,sub(5,2)) -> 4
  15.   div(-7,2) -> -3
  16.  
  17. Invalid examples:
  18.   add(1,) -> Missing second argument
  19.   add(1 2) -> Missing comma
  20.   add(1,2 -> Missing closing parenthesis
  21.   add(1,2,3) -> Too many arguments
  22.   foo(1,2) -> Unknown function
  23.   div(5,0) -> Division by zero
  24.  
  25. ASSUMPTIONS:
  26. - Each function takes exactly 2 arguments.
  27. - Numbers are signed integers.
  28. - Spaces are allowed around tokens.
  29. - Division truncates toward zero.
  30. - Exponents must be nonnegative.
  31. - 0^0 = 1.
  32. - Results must fit signed 32-bit integers.
  33.  
  34. APPROACH:
  35. - Iterative parser (no recursion).
  36. - values stack stores evaluated values.
  37. - frames stack stores unfinished function calls.
  38. - Each frame tracks the next expected token.
  39. - Report the first detected error and its index.
  40.  
  41. TIME: O(n), assuming fixed-width arithmetic.
  42. SPACE: O(d), where d is nesting depth.
  43. */
  44.  
  45. function evaluateExpression(s) {
  46. const values = [];
  47. const frames = [];
  48. let i = 0;
  49.  
  50. const MIN_INT = -2147483648;
  51. const MAX_INT = 2147483647;
  52.  
  53. function fail(message, index = i) {
  54. throw new Error(
  55. `${message} at index ${index}`
  56. );
  57. }
  58.  
  59. function skipSpaces() {
  60. while (i < s.length && s[i] === ' ') {
  61. i++;
  62. }
  63. }
  64.  
  65. function isDigit(ch) {
  66. return ch >= '0' && ch <= '9';
  67. }
  68.  
  69. function isLetter(ch) {
  70. return ch >= 'a' && ch <= 'z';
  71. }
  72.  
  73. function isNumberStart(ch) {
  74. return ch === '-' || isDigit(ch);
  75. }
  76.  
  77. function checkRange(value, index) {
  78. if (
  79. !Number.isSafeInteger(value) ||
  80. value < MIN_INT ||
  81. value > MAX_INT
  82. ) {
  83. fail("Integer out of 32-bit range", index);
  84. }
  85. return value;
  86. }
  87.  
  88. function parseNumber() {
  89. const start = i;
  90.  
  91. if (s[i] === '-') i++;
  92.  
  93. // A minus sign must be followed by a digit.
  94. if (!isDigit(s[i])) {
  95. fail("Expected digit after minus sign", i);
  96. }
  97.  
  98. while (i < s.length && isDigit(s[i])) {
  99. i++;
  100. }
  101.  
  102. const value = Number(s.slice(start, i));
  103. return checkRange(value, start);
  104. }
  105.  
  106. function parseOperation() {
  107. const start = i;
  108.  
  109. while (i < s.length && isLetter(s[i])) {
  110. i++;
  111. }
  112.  
  113. const op = s.slice(start, i);
  114.  
  115. if (!["add", "sub", "mul", "div", "pow"].includes(op)) {
  116. fail(`Unknown operation '${op}'`, start);
  117. }
  118.  
  119. return op;
  120. }
  121.  
  122. function applyCall(op, x, y, index) {
  123. let result;
  124.  
  125. if (op === "add") {
  126. result = x + y;
  127. } else if (op === "sub") {
  128. result = x - y;
  129. } else if (op === "mul") {
  130. result = x * y;
  131. } else if (op === "div") {
  132. if (y === 0) {
  133. fail("Division by zero", index);
  134. }
  135. result = Math.trunc(x / y);
  136. } else if (op === "pow") {
  137. if (y < 0) {
  138. fail("Negative exponent", index);
  139. }
  140. result = Math.pow(x, y);
  141. }
  142.  
  143. return checkRange(result, index);
  144. }
  145.  
  146. /*
  147.   Parser states:
  148.  
  149.   EXPECT_EXPR:
  150.   Need an integer or function call.
  151.  
  152.   EXPECT_OPEN:
  153.   Need '(' after function name.
  154.  
  155.   EXPECT_COMMA:
  156.   First argument is complete; need ','.
  157.  
  158.   EXPECT_SECOND:
  159.   Need the second argument.
  160.  
  161.   EXPECT_CLOSE:
  162.   Second argument is complete; need ')'.
  163.   */
  164.  
  165. // What is expected at the root?
  166. let rootState = "EXPECT_EXPR";
  167.  
  168. function getState() {
  169. if (frames.length === 0) {
  170. return rootState;
  171. }
  172. return frames[frames.length - 1].state;
  173. }
  174.  
  175. function completeExpression(value) {
  176. values.push(value);
  177.  
  178. if (frames.length === 0) {
  179. rootState = "DONE";
  180. return;
  181. }
  182.  
  183. const frame = frames[frames.length - 1];
  184.  
  185. if (frame.state === "EXPECT_EXPR") {
  186. frame.state = "EXPECT_COMMA";
  187. } else if (frame.state === "EXPECT_SECOND") {
  188. frame.state = "EXPECT_CLOSE";
  189. } else {
  190. fail("Unexpected expression");
  191. }
  192. }
  193.  
  194. while (true) {
  195. skipSpaces();
  196.  
  197. if (i >= s.length) break;
  198.  
  199. const state = getState();
  200. const ch = s[i];
  201.  
  202. // State 1: Need an expression.
  203. if (
  204. state === "EXPECT_EXPR" ||
  205. state === "EXPECT_SECOND"
  206. ) {
  207. if (isNumberStart(ch)) {
  208. const number = parseNumber();
  209. completeExpression(number);
  210. } else if (isLetter(ch)) {
  211. const opStart = i;
  212. const op = parseOperation();
  213.  
  214. frames.push({
  215. op,
  216. opStart,
  217. state: "EXPECT_OPEN"
  218. });
  219. } else {
  220. fail("Expected number or function");
  221. }
  222. }
  223.  
  224. // State 2: Need '('.
  225. else if (state === "EXPECT_OPEN") {
  226. if (ch !== "(") {
  227. fail("Expected '(' after operation");
  228. }
  229.  
  230. frames[frames.length - 1].state = "EXPECT_EXPR";
  231. i++;
  232. }
  233.  
  234. // State 3: Need ','.
  235. else if (state === "EXPECT_COMMA") {
  236. if (ch !== ",") {
  237. fail("Expected ',' after first argument");
  238. }
  239.  
  240. frames[frames.length - 1].state = "EXPECT_SECOND";
  241. i++;
  242. }
  243.  
  244. // State 4: Need ')'.
  245. else if (state === "EXPECT_CLOSE") {
  246. if (ch !== ")") {
  247. fail("Expected ')' after second argument");
  248. }
  249.  
  250. const frame = frames.pop();
  251. const y = values.pop();
  252. const x = values.pop();
  253.  
  254. const result = applyCall(
  255. frame.op,
  256. x,
  257. y,
  258. i
  259. );
  260.  
  261. i++;
  262.  
  263. // Completed function becomes one expression
  264. // for its parent (or the root).
  265. completeExpression(result);
  266. }
  267.  
  268. // State 5: Root expression already complete.
  269. else if (state === "DONE") {
  270. fail("Unexpected character after expression");
  271. }
  272. }
  273.  
  274. // End-of-input validation.
  275. if (frames.length > 0) {
  276. const state = getState();
  277.  
  278. if (state === "EXPECT_OPEN") {
  279. fail("Missing '(' after operation");
  280. }
  281. if (state === "EXPECT_EXPR" ||
  282. state === "EXPECT_SECOND") {
  283. fail("Missing argument");
  284. }
  285. if (state === "EXPECT_COMMA") {
  286. fail("Missing comma and second argument");
  287. }
  288. if (state === "EXPECT_CLOSE") {
  289. fail("Missing closing ')'");
  290. }
  291. }
  292.  
  293. if (rootState !== "DONE" || values.length !== 1) {
  294. fail("Incomplete expression");
  295. }
  296.  
  297. return values[0];
  298. }
  299.  
  300.  
  301. // ---------------- TEST HARNESS ----------------
  302.  
  303. const tests = [
  304. // Valid expressions
  305. ["add(1,2)", 3],
  306. ["add(1,sub(5,2))", 4],
  307. ["div(-7,2)", -3],
  308. ["pow(0,0)", 1],
  309. ["sub(add(7,8),sub(3,1))", 13],
  310. [" add( 1 , mul( 2 , 3 ) ) ", 7],
  311. ["-42", -42],
  312.  
  313. // Invalid expressions: expected error fragments
  314. ["add(1,)", "Expected number or function"],
  315. ["add(1 2)", "Expected ','"],
  316. ["add(1,2", "Missing closing"],
  317. ["add(1,2,3)", "Expected ')'"],
  318. ["foo(1,2)", "Unknown operation"],
  319. ["div(5,0)", "Division by zero"],
  320. ["pow(2,-1)", "Negative exponent"],
  321. ["add(1,2))", "Unexpected character"],
  322. ["add(1)", "Expected ','"],
  323. ["add(-,2)", "Expected digit"],
  324. ["add(2147483647,1)", "Integer out of 32-bit range"],
  325. ["", "Incomplete expression"]
  326. ];
  327.  
  328. tests.forEach(([input, expected], index) => {
  329. let actual;
  330.  
  331. try {
  332. actual = evaluateExpression(input);
  333. } catch (err) {
  334. actual = err.message;
  335. }
  336.  
  337. const passed =
  338. typeof expected === "number"
  339. ? actual === expected
  340. : typeof actual === "string" &&
  341. actual.includes(expected);
  342.  
  343. console.log(
  344. `Test ${index + 1}: ${passed ? "PASS" : "FAIL"}\n` +
  345. `Input: ${JSON.stringify(input)}\n` +
  346. `Expected: ${expected}\n` +
  347. `Actual: ${actual}\n`
  348. );
  349. });
  350.  
Success #stdin #stdout 0.03s 5640KB
stdin
Standard input is empty
stdout
Test 1: PASS
Input: "add(1,2)"
Expected: 3
Actual: 3

Test 2: PASS
Input: "add(1,sub(5,2))"
Expected: 4
Actual: 4

Test 3: PASS
Input: "div(-7,2)"
Expected: -3
Actual: -3

Test 4: PASS
Input: "pow(0,0)"
Expected: 1
Actual: 1

Test 5: PASS
Input: "sub(add(7,8),sub(3,1))"
Expected: 13
Actual: 13

Test 6: PASS
Input: "  add( 1 , mul( 2 , 3 ) )  "
Expected: 7
Actual: 7

Test 7: PASS
Input: "-42"
Expected: -42
Actual: -42

Test 8: PASS
Input: "add(1,)"
Expected: Expected number or function
Actual: Expected number or function at index 6

Test 9: PASS
Input: "add(1 2)"
Expected: Expected ','
Actual: Expected ',' after first argument at index 6

Test 10: PASS
Input: "add(1,2"
Expected: Missing closing
Actual: Missing closing ')' at index 7

Test 11: PASS
Input: "add(1,2,3)"
Expected: Expected ')'
Actual: Expected ')' after second argument at index 7

Test 12: PASS
Input: "foo(1,2)"
Expected: Unknown operation
Actual: Unknown operation 'foo' at index 0

Test 13: PASS
Input: "div(5,0)"
Expected: Division by zero
Actual: Division by zero at index 7

Test 14: PASS
Input: "pow(2,-1)"
Expected: Negative exponent
Actual: Negative exponent at index 8

Test 15: PASS
Input: "add(1,2))"
Expected: Unexpected character
Actual: Unexpected character after expression at index 8

Test 16: PASS
Input: "add(1)"
Expected: Expected ','
Actual: Expected ',' after first argument at index 5

Test 17: PASS
Input: "add(-,2)"
Expected: Expected digit
Actual: Expected digit after minus sign at index 5

Test 18: PASS
Input: "add(2147483647,1)"
Expected: Integer out of 32-bit range
Actual: Integer out of 32-bit range at index 16

Test 19: PASS
Input: ""
Expected: Incomplete expression
Actual: Incomplete expression at index 0