Skip to content

Commit

Permalink
fix(generators): Fix an operator precedence issue in the math_number_…
Browse files Browse the repository at this point in the history
…property generators to remove extra parentheses (#5685)

* Fixed issue where the mathIsPrime function inserted extra parenthesis around certain blocks.
* Added tests to generated JS
* Updated generated code in Lua
* Updated Generated code for tests in Dart
* Updated generated code for tests in PHP
* Updated generated code for tests in Python
* Also changed var to const and let.

Co-authored-by: jeremyjacob123 <43049656+jeremyjacob123@users.noreply.github.com>
Co-authored-by: LouisCatala <86700310+LouisCatala@users.noreply.github.com>
Co-authored-by: jeremyjacob123 <43049656+jeremyjacob123@users.noreply.github.com>
  • Loading branch information
3 people authored and NeilFraser committed Jan 28, 2022
1 parent 85a851c commit c75eab2
Show file tree
Hide file tree
Showing 11 changed files with 808 additions and 710 deletions.
318 changes: 151 additions & 167 deletions generators/dart/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,65 +164,64 @@ Dart['math_constant'] = function(block) {
Dart['math_number_property'] = function(block) {
// Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false.
const number_to_check =
Dart.valueToCode(block, 'NUMBER_TO_CHECK', Dart.ORDER_MULTIPLICATIVE);
if (!number_to_check) {
return ['false', Dart.ORDER_ATOMIC];
}
const dropdown_property = block.getFieldValue('PROPERTY');
const PROPERTIES = {
'EVEN': [' % 2 == 0', Dart.ORDER_MULTIPLICATIVE,
Dart.ORDER_EQUALITY],
'ODD': [' % 2 == 1', Dart.ORDER_MULTIPLICATIVE,
Dart.ORDER_EQUALITY],
'WHOLE': [' % 1 == 0', Dart.ORDER_MULTIPLICATIVE,
Dart.ORDER_EQUALITY],
'POSITIVE': [' > 0', Dart.ORDER_RELATIONAL,
Dart.ORDER_RELATIONAL],
'NEGATIVE': [' < 0', Dart.ORDER_RELATIONAL,
Dart.ORDER_RELATIONAL],
'DIVISIBLE_BY': [null, Dart.ORDER_MULTIPLICATIVE,
Dart.ORDER_EQUALITY],
'PRIME': [null, Dart.ORDER_NONE,
Dart.ORDER_UNARY_POSTFIX]
};
const dropdownProperty = block.getFieldValue('PROPERTY');
const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty];
const numberToCheck = Dart.valueToCode(block, 'NUMBER_TO_CHECK',
inputOrder) || '0';
let code;
if (dropdown_property === 'PRIME') {
if (dropdownProperty === 'PRIME') {
// Prime is a special case as it is not a one-liner test.
Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;';
const functionName = Dart.provideFunction_('math_isPrime', `
bool ${Dart.FUNCTION_NAME_PLACEHOLDER_}(n) {
// https://en.wikipedia.org/wiki/Primality_test#Naive_methods
if (n == 2 || n == 3) {
return true;
}
// False if n is null, negative, is 1, or not whole.
// And false if n is divisible by 2 or 3.
if (n == null || n <= 1 || n % 1 != 0 || n % 2 == 0 || n % 3 == 0) {
return false;
}
// Check all the numbers of form 6k +/- 1, up to sqrt(n).
for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {
if (n % (x - 1) == 0 || n % (x + 1) == 0) {
return false;
Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
const functionName = Dart.provideFunction_(
'math_isPrime',
['bool ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(n) {',
' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' if (n == 2 || n == 3) {',
' return true;',
' }',
' // False if n is null, negative, is 1, or not whole.',
' // And false if n is divisible by 2 or 3.',
' if (n == null || n <= 1 || n % 1 != 0 || n % 2 == 0 ||' +
' n % 3 == 0) {',
' return false;',
' }',
' // Check all the numbers of form 6k +/- 1, up to sqrt(n).',
' for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {',
' if (n % (x - 1) == 0 || n % (x + 1) == 0) {',
' return false;',
' }',
' }',
' return true;',
'}']);
code = functionName + '(' + numberToCheck + ')';
} else if (dropdownProperty === 'DIVISIBLE_BY') {
const divisor = Dart.valueToCode(block, 'DIVISOR',
Dart.ORDER_MULTIPLICATIVE) || '0';
if (divisor === '0') {
return ['false', Dart.ORDER_ATOMIC];
}
code = numberToCheck + ' % ' + divisor + ' == 0';
} else {
code = numberToCheck + suffix;
}
return true;
}
`);
code = functionName + '(' + number_to_check + ')';
return [code, Dart.ORDER_UNARY_POSTFIX];
}
switch (dropdown_property) {
case 'EVEN':
code = number_to_check + ' % 2 == 0';
break;
case 'ODD':
code = number_to_check + ' % 2 == 1';
break;
case 'WHOLE':
code = number_to_check + ' % 1 == 0';
break;
case 'POSITIVE':
code = number_to_check + ' > 0';
break;
case 'NEGATIVE':
code = number_to_check + ' < 0';
break;
case 'DIVISIBLE_BY':
const divisor =
Dart.valueToCode(block, 'DIVISOR', Dart.ORDER_MULTIPLICATIVE);
if (!divisor) {
return ['false', Dart.ORDER_ATOMIC];
}
code = number_to_check + ' % ' + divisor + ' == 0';
break;
}
return [code, Dart.ORDER_EQUALITY];
return [code, outputOrder];
};

Dart['math_change'] = function(block) {
Expand All @@ -247,76 +246,70 @@ Dart['math_on_list'] = function(block) {
let code;
switch (func) {
case 'SUM': {
const functionName = Dart.provideFunction_('math_sum', `
num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List<num> myList) {
num sumVal = 0;
myList.forEach((num entry) {sumVal += entry;});
return sumVal;
}
`);
const functionName = Dart.provideFunction_('math_sum', [
'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List<num> myList) {',
' num sumVal = 0;',
' myList.forEach((num entry) {sumVal += entry;});', ' return sumVal;',
'}'
]);
code = functionName + '(' + list + ')';
break;
}
case 'MIN': {
Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;';
const functionName = Dart.provideFunction_('math_min', `
num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List<num> myList) {
if (myList.isEmpty) return null;
num minVal = myList[0];
myList.forEach((num entry) {minVal = Math.min(minVal, entry);});
return minVal;
}
`);
const functionName = Dart.provideFunction_('math_min', [
'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List<num> myList) {',
' if (myList.isEmpty) return null;', ' num minVal = myList[0];',
' myList.forEach((num entry) ' +
'{minVal = Math.min(minVal, entry);});',
' return minVal;', '}'
]);
code = functionName + '(' + list + ')';
break;
}
case 'MAX': {
Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;';
const functionName = Dart.provideFunction_('math_max', `
num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List<num> myList) {
if (myList.isEmpty) return null;
num maxVal = myList[0];
myList.forEach((num entry) {maxVal = Math.max(maxVal, entry);});
return maxVal;
}
`);
const functionName = Dart.provideFunction_('math_max', [
'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List<num> myList) {',
' if (myList.isEmpty) return null;', ' num maxVal = myList[0];',
' myList.forEach((num entry) ' +
'{maxVal = Math.max(maxVal, entry);});',
' return maxVal;', '}'
]);
code = functionName + '(' + list + ')';
break;
}
case 'AVERAGE': {
// This operation exclude null and values that are not int or float:
// math_mean([null,null,"aString",1,9]) -> 5.0
const functionName = Dart.provideFunction_('math_mean', `
num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) {
// First filter list for numbers only.
List localList = new List.from(myList);
localList.removeWhere((a) => a is! num);
if (localList.isEmpty) return null;
num sumVal = 0;
localList.forEach((var entry) {sumVal += entry;});
return sumVal / localList.length;
}
`);
const functionName = Dart.provideFunction_('math_mean', [
'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {',
' // First filter list for numbers only.',
' List localList = new List.from(myList);',
' localList.removeWhere((a) => a is! num);',
' if (localList.isEmpty) return null;', ' num sumVal = 0;',
' localList.forEach((var entry) {sumVal += entry;});',
' return sumVal / localList.length;', '}'
]);
code = functionName + '(' + list + ')';
break;
}
case 'MEDIAN': {
const functionName = Dart.provideFunction_('math_median', `
num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) {
// First filter list for numbers only, then sort, then return middle value
// or the average of two middle values if list has an even number of elements.
List localList = new List.from(myList);
localList.removeWhere((a) => a is! num);
if (localList.isEmpty) return null;
localList.sort((a, b) => (a - b));
int index = localList.length ~/ 2;
if (localList.length % 2 == 1) {
return localList[index];
} else {
return (localList[index - 1] + localList[index]) / 2;
}
}
`);
const functionName = Dart.provideFunction_('math_median', [
'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {',
' // First filter list for numbers only, then sort, ' +
'then return middle value',
' // or the average of two middle values if list has an ' +
'even number of elements.',
' List localList = new List.from(myList);',
' localList.removeWhere((a) => a is! num);',
' if (localList.isEmpty) return null;',
' localList.sort((a, b) => (a - b));',
' int index = localList.length ~/ 2;',
' if (localList.length % 2 == 1) {', ' return localList[index];',
' } else {',
' return (localList[index - 1] + localList[index]) / 2;', ' }', '}'
]);
code = functionName + '(' + list + ')';
break;
}
Expand All @@ -325,67 +318,63 @@ num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) {
// As a list of numbers can contain more than one mode,
// the returned result is provided as an array.
// Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1]
const functionName = Dart.provideFunction_('math_modes', `
List ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List values) {
List modes = [];
List counts = [];
int maxCount = 0;
for (int i = 0; i < values.length; i++) {
var value = values[i];
bool found = false;
int thisCount;
for (int j = 0; j < counts.length; j++) {
if (counts[j][0] == value) {
thisCount = ++counts[j][1];
found = true;
break;
}
}
if (!found) {
counts.add([value, 1]);
thisCount = 1;
}
maxCount = Math.max(thisCount, maxCount);
}
for (int j = 0; j < counts.length; j++) {
if (counts[j][1] == maxCount) {
modes.add(counts[j][0]);
}
}
return modes;
}
`);
const functionName = Dart.provideFunction_('math_modes', [
'List ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List values) {',
' List modes = [];',
' List counts = [];',
' int maxCount = 0;',
' for (int i = 0; i < values.length; i++) {',
' var value = values[i];',
' bool found = false;',
' int thisCount;',
' for (int j = 0; j < counts.length; j++) {',
' if (counts[j][0] == value) {',
' thisCount = ++counts[j][1];',
' found = true;',
' break;',
' }',
' }',
' if (!found) {',
' counts.add([value, 1]);',
' thisCount = 1;',
' }',
' maxCount = Math.max(thisCount, maxCount);',
' }',
' for (int j = 0; j < counts.length; j++) {',
' if (counts[j][1] == maxCount) {',
' modes.add(counts[j][0]);',
' }',
' }',
' return modes;',
'}'
]);
code = functionName + '(' + list + ')';
break;
}
case 'STD_DEV': {
Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;';
const functionName = Dart.provideFunction_('math_standard_deviation', `
num ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) {
// First filter list for numbers only.
List numbers = new List.from(myList);
numbers.removeWhere((a) => a is! num);
if (numbers.isEmpty) return null;
num n = numbers.length;
num sum = 0;
numbers.forEach((x) => sum += x);
num mean = sum / n;
num sumSquare = 0;
numbers.forEach((x) => sumSquare += Math.pow(x - mean, 2));
return Math.sqrt(sumSquare / n);
}
`);
const functionName = Dart.provideFunction_('math_standard_deviation', [
'num ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {',
' // First filter list for numbers only.',
' List numbers = new List.from(myList);',
' numbers.removeWhere((a) => a is! num);',
' if (numbers.isEmpty) return null;', ' num n = numbers.length;',
' num sum = 0;', ' numbers.forEach((x) => sum += x);',
' num mean = sum / n;', ' num sumSquare = 0;',
' numbers.forEach((x) => sumSquare += ' +
'Math.pow(x - mean, 2));',
' return Math.sqrt(sumSquare / n);', '}'
]);
code = functionName + '(' + list + ')';
break;
}
case 'RANDOM': {
Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;';
const functionName = Dart.provideFunction_('math_random_item', `
dynamic ${Dart.FUNCTION_NAME_PLACEHOLDER_}(List myList) {
int x = new Math.Random().nextInt(myList.length);
return myList[x];
}
`);
const functionName = Dart.provideFunction_('math_random_item', [
'dynamic ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(List myList) {',
' int x = new Math.Random().nextInt(myList.length);',
' return myList[x];', '}'
]);
code = functionName + '(' + list + ')';
break;
}
Expand Down Expand Up @@ -422,17 +411,12 @@ Dart['math_random_int'] = function(block) {
Dart.definitions_['import_dart_math'] = 'import \'dart:math\' as Math;';
const argument0 = Dart.valueToCode(block, 'FROM', Dart.ORDER_NONE) || '0';
const argument1 = Dart.valueToCode(block, 'TO', Dart.ORDER_NONE) || '0';
const functionName = Dart.provideFunction_('math_random_int', `
int ${Dart.FUNCTION_NAME_PLACEHOLDER_}(num a, num b) {
if (a > b) {
// Swap a and b to ensure a is smaller.
num c = a;
a = b;
b = c;
}
return new Math.Random().nextInt(b - a + 1) + a;
}
`);
const functionName = Dart.provideFunction_('math_random_int', [
'int ' + Dart.FUNCTION_NAME_PLACEHOLDER_ + '(num a, num b) {',
' if (a > b) {', ' // Swap a and b to ensure a is smaller.',
' num c = a;', ' a = b;', ' b = c;', ' }',
' return new Math.Random().nextInt(b - a + 1) + a;', '}'
]);
const code = functionName + '(' + argument0 + ', ' + argument1 + ')';
return [code, Dart.ORDER_UNARY_POSTFIX];
};
Expand Down
Loading

0 comments on commit c75eab2

Please sign in to comment.