From 24e4e69320edc136301b696929e8c49709c0a3da Mon Sep 17 00:00:00 2001 From: mreichhoff Date: Sun, 14 Jul 2024 15:18:31 -0400 Subject: [PATCH] Only reset empty Hanzi Math results of subtraction (#47) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously, operations like 我+你+我 would return results. This was because empty results of prior operations effectively reset the result, but we only want that with subtraction. 我+你+我 now returns []. Note that this does not address self-adds, which are still broken. It also continues adding all parents in cases like: 我-我+我. The same transitivity is true for normal operations (so 力+口 returns many characters with 另 or 加 as a component, intentionally). --- public/js/modules/hanzi-math.js | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/public/js/modules/hanzi-math.js b/public/js/modules/hanzi-math.js index 1234d17..d5aab7a 100644 --- a/public/js/modules/hanzi-math.js +++ b/public/js/modules/hanzi-math.js @@ -113,6 +113,7 @@ function evaluate(input) { } let leftOperandList = null; let nextOperator = null; + let previousOperation = null; for (const character of input) { // no left side yet? set it and move on. // note that leftOperandList can later become empty, which is then handled in the plus operation @@ -122,6 +123,9 @@ function evaluate(input) { } // it's an operator, so note that as our next operation and move on. if (operators.has(character)) { + if (nextOperator !== null) { + previousOperation = nextOperator; + } nextOperator = character; continue; } @@ -155,16 +159,16 @@ function evaluate(input) { } } } else { - // Nothing there now, due to subtraction to 0 or due to not finding results of an add? - // Add the right operand and return its compounds... - // TODO: this does mean adds of 3 or more items can be weird, with the first addition going to [] + // Nothing there now, due to subtraction to [] or due to not finding results of an add. + // Add the right operand and return its compounds, but first + // check for previous subtraction before special casing the empty list. + // Otherwise, adds of 3 or more items can be weird, with the first addition going to [] // and then the next addition adding items that probably shouldn't be there // example: // 我+你-->no result // 我+你+我-->results as though it was just 我. - // Should probably only do special empty handling - // if the prior operation was a subtraction... - if (leftOperandList.length < 1) { + // The `previousOperation` check avoids that. + if (previousOperation === '-' && leftOperandList.length < 1) { leftOperandList.push(character); } // if it's addition, find transitive compounds as the set of candidates,