Skip to content

Commit 6da1c17

Browse files
committed
fix json_index_of_value (and a double evaluation in it)
1 parent 30aaa6f commit 6da1c17

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

src/compiler/irgen.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -357,8 +357,8 @@ class ScriptTreeGenerator {
357357
array: this.descendInputOfBlock(block, 'ARR').toType(InputType.ARRAY)
358358
});
359359
case 'json_index_of_value':
360-
return new IntermediateInput(InputOpcode.JSON_INDEX_OF_VALUE, InputType.NUMBER, {
361-
value: this.descendInputOfBlock(block, 'VALUE').toType(InputType.ANY),
360+
return new IntermediateInput(InputOpcode.JSON_INDEX_OF_VALUE, InputType.NUMBER_WHOLE | InputType.STRING_NAN, {
361+
value: this.descendInputOfBlock(block, 'VALUE'),
362362
array: this.descendInputOfBlock(block, 'ARR').toType(InputType.ARRAY)
363363
});
364364
case 'json_add_item':

src/compiler/jsexecute.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,18 @@ runtimeFunctions.mergeObjects = `const mergeObjects = (a, b) => {
4040
return Object.fromEntries(Object.entries(a).concat(Object.entries(b)));
4141
};`;
4242

43+
/**
44+
* Find the 0-indexed index of an item in an array.
45+
* @param {Array<*>} array The array.
46+
* @param {*} item The item to search for
47+
* @returns {number | string} The 0-indexed index of the item in the list, otherwise empty string
48+
*/
49+
runtimeFunctions.arrayIndexOf = `const arrayIndexOf = (array, item) => {
50+
const index = array.indexOf(item);
51+
if (index === -1) return "";
52+
return index;
53+
}`;
54+
4355
/**
4456
* Determine whether the current tick is likely stuck.
4557
* This implements similar functionality to the warp timer found in Scratch.

src/compiler/jsgen.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ class JSGenerator {
287287
case InputOpcode.JSON_VALUE_OF_INDEX:
288288
return `(${this.descendInput(node.array)}[${this.descendInput(node.index)}] ?? "")`;
289289
case InputOpcode.JSON_INDEX_OF_VALUE:
290-
return `(${this.descendInput(node.array)}.indexOf(${this.descendInput(node.value)}) !== -1 ? ${this.descendInput(node.array)}.indexOf(${this.descendInput(node.value)}) : "")`;
290+
return `arrayIndexOf(${this.descendInput(node.array)}, ${this.descendInput(node.value)})`;
291291
case InputOpcode.JSON_ADD_ITEM:
292292
return `(array = ${this.descendInput(node.array)}.slice(0), array.push(${this.descendInput(node.item)}), array)`;
293293
case InputOpcode.JSON_REPLACE_INDEX:

0 commit comments

Comments
 (0)