chore: Use ES6 template strings in CSS and code generators (#5902)

* Unindent CSS, save 3 kb of code.
* Convert generator functions to template strings. 
This resolves #5761.
This commit is contained in:
Neil Fraser
2022-01-28 17:58:43 -08:00
committed by GitHub
parent a31003fab9
commit 1f6a1bd8d9
39 changed files with 2194 additions and 2062 deletions

View File

@@ -22,11 +22,12 @@ JavaScript['colour_picker'] = function(block) {
JavaScript['colour_random'] = function(block) {
// Generate a random colour.
const functionName = JavaScript.provideFunction_('colourRandom', [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '() {',
' var num = Math.floor(Math.random() * Math.pow(2, 24));',
' return \'#\' + (\'00000\' + num.toString(16)).substr(-6);', '}'
]);
const functionName = JavaScript.provideFunction_('colourRandom', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}() {
var num = Math.floor(Math.random() * Math.pow(2, 24));
return '#' + ('00000' + num.toString(16)).substr(-6);
}
`);
const code = functionName + '()';
return [code, JavaScript.ORDER_FUNCTION_CALL];
};
@@ -38,16 +39,17 @@ JavaScript['colour_rgb'] = function(block) {
JavaScript.valueToCode(block, 'GREEN', JavaScript.ORDER_NONE) || 0;
const blue =
JavaScript.valueToCode(block, 'BLUE', JavaScript.ORDER_NONE) || 0;
const functionName = JavaScript.provideFunction_('colourRgb', [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(r, g, b) {',
' r = Math.max(Math.min(Number(r), 100), 0) * 2.55;',
' g = Math.max(Math.min(Number(g), 100), 0) * 2.55;',
' b = Math.max(Math.min(Number(b), 100), 0) * 2.55;',
' r = (\'0\' + (Math.round(r) || 0).toString(16)).slice(-2);',
' g = (\'0\' + (Math.round(g) || 0).toString(16)).slice(-2);',
' b = (\'0\' + (Math.round(b) || 0).toString(16)).slice(-2);',
' return \'#\' + r + g + b;', '}'
]);
const functionName = JavaScript.provideFunction_('colourRgb', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) {
r = Math.max(Math.min(Number(r), 100), 0) * 2.55;
g = Math.max(Math.min(Number(g), 100), 0) * 2.55;
b = Math.max(Math.min(Number(b), 100), 0) * 2.55;
r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2);
g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2);
b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2);
return '#' + r + g + b;
}
`);
const code = functionName + '(' + red + ', ' + green + ', ' + blue + ')';
return [code, JavaScript.ORDER_FUNCTION_CALL];
};
@@ -55,28 +57,29 @@ JavaScript['colour_rgb'] = function(block) {
JavaScript['colour_blend'] = function(block) {
// Blend two colours together.
const c1 = JavaScript.valueToCode(block, 'COLOUR1', JavaScript.ORDER_NONE) ||
'\'#000000\'';
"'#000000'";
const c2 = JavaScript.valueToCode(block, 'COLOUR2', JavaScript.ORDER_NONE) ||
'\'#000000\'';
"'#000000'";
const ratio =
JavaScript.valueToCode(block, 'RATIO', JavaScript.ORDER_NONE) || 0.5;
const functionName = JavaScript.provideFunction_('colourBlend', [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(c1, c2, ratio) {',
' ratio = Math.max(Math.min(Number(ratio), 1), 0);',
' var r1 = parseInt(c1.substring(1, 3), 16);',
' var g1 = parseInt(c1.substring(3, 5), 16);',
' var b1 = parseInt(c1.substring(5, 7), 16);',
' var r2 = parseInt(c2.substring(1, 3), 16);',
' var g2 = parseInt(c2.substring(3, 5), 16);',
' var b2 = parseInt(c2.substring(5, 7), 16);',
' var r = Math.round(r1 * (1 - ratio) + r2 * ratio);',
' var g = Math.round(g1 * (1 - ratio) + g2 * ratio);',
' var b = Math.round(b1 * (1 - ratio) + b2 * ratio);',
' r = (\'0\' + (r || 0).toString(16)).slice(-2);',
' g = (\'0\' + (g || 0).toString(16)).slice(-2);',
' b = (\'0\' + (b || 0).toString(16)).slice(-2);',
' return \'#\' + r + g + b;', '}'
]);
const functionName = JavaScript.provideFunction_('colourBlend', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(c1, c2, ratio) {
ratio = Math.max(Math.min(Number(ratio), 1), 0);
var r1 = parseInt(c1.substring(1, 3), 16);
var g1 = parseInt(c1.substring(3, 5), 16);
var b1 = parseInt(c1.substring(5, 7), 16);
var r2 = parseInt(c2.substring(1, 3), 16);
var g2 = parseInt(c2.substring(3, 5), 16);
var b2 = parseInt(c2.substring(5, 7), 16);
var r = Math.round(r1 * (1 - ratio) + r2 * ratio);
var g = Math.round(g1 * (1 - ratio) + g2 * ratio);
var b = Math.round(b1 * (1 - ratio) + b2 * ratio);
r = ('0' + (r || 0).toString(16)).slice(-2);
g = ('0' + (g || 0).toString(16)).slice(-2);
b = ('0' + (b || 0).toString(16)).slice(-2);
return '#' + r + g + b;
}
`);
const code = functionName + '(' + c1 + ', ' + c2 + ', ' + ratio + ')';
return [code, JavaScript.ORDER_FUNCTION_CALL];
};

View File

@@ -35,11 +35,15 @@ JavaScript['lists_create_with'] = function(block) {
JavaScript['lists_repeat'] = function(block) {
// Create a list with one element repeated.
const functionName = JavaScript.provideFunction_('listsRepeat', [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(value, n) {',
' var array = [];', ' for (var i = 0; i < n; i++) {',
' array[i] = value;', ' }', ' return array;', '}'
]);
const functionName = JavaScript.provideFunction_('listsRepeat', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(value, n) {
var array = [];
for (var i = 0; i < n; i++) {
array[i] = value;
}
return array;
}
`);
const element =
JavaScript.valueToCode(block, 'ITEM', JavaScript.ORDER_NONE) || 'null';
const repeatCount =
@@ -67,7 +71,7 @@ JavaScript['lists_indexOf'] = function(block) {
const operator =
block.getFieldValue('END') === 'FIRST' ? 'indexOf' : 'lastIndexOf';
const item =
JavaScript.valueToCode(block, 'FIND', JavaScript.ORDER_NONE) || '\'\'';
JavaScript.valueToCode(block, 'FIND', JavaScript.ORDER_NONE) || "''";
const list =
JavaScript.valueToCode(block, 'VALUE', JavaScript.ORDER_MEMBER) || '[]';
const code = list + '.' + operator + '(' + item + ')';
@@ -136,13 +140,16 @@ JavaScript['lists_getIndex'] = function(block) {
break;
}
case ('RANDOM'): {
const functionName = JavaScript.provideFunction_('listsGetRandomItem', [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(list, remove) {',
' var x = Math.floor(Math.random() * list.length);', ' if (remove) {',
' return list.splice(x, 1)[0];', ' } else {', ' return list[x];',
' }', '}'
]);
const functionName = JavaScript.provideFunction_('listsGetRandomItem', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(list, remove) {
var x = Math.floor(Math.random() * list.length);
if (remove) {
return list.splice(x, 1)[0];
} else {
return list[x];
}
}
`);
const code = functionName + '(' + list + ', ' + (mode !== 'GET') + ')';
if (mode === 'GET' || mode === 'GET_REMOVE') {
return [code, JavaScript.ORDER_FUNCTION_CALL];
@@ -309,23 +316,22 @@ JavaScript['lists_getSublist'] = function(block) {
'FIRST': 'First',
'LAST': 'Last',
'FROM_START': 'FromStart',
'FROM_END': 'FromEnd'
'FROM_END': 'FromEnd',
};
// The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter.
const at1Param =
(where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : '';
const at2Param =
(where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : '';
const functionName = JavaScript.provideFunction_(
'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(sequence' +
// The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter.
((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' :
'') +
((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' :
'') +
') {',
getSubstringIndex('sequence', where1, 'at1') + ';',
' var end = ' + getSubstringIndex('sequence', where2, 'at2') +
' + 1;',
' return sequence.slice(start, end);', '}'
]);
'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(sequence${at1Param}${at2Param}) {
var start = ${getSubstringIndex('sequence', where1, 'at1')};
var end = ${getSubstringIndex('sequence', where2, 'at2')} + 1;
return sequence.slice(start, end);
}
`);
code = functionName + '(' + list +
// The value for 'FROM_END' and 'FROM_START' depends on `at` so we
// pass it.
@@ -344,19 +350,20 @@ JavaScript['lists_sort'] = function(block) {
const direction = block.getFieldValue('DIRECTION') === '1' ? 1 : -1;
const type = block.getFieldValue('TYPE');
const getCompareFunctionName =
JavaScript.provideFunction_('listsGetSortCompare', [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(type, direction) {',
' var compareFuncs = {', ' "NUMERIC": function(a, b) {',
' return Number(a) - Number(b); },',
' "TEXT": function(a, b) {',
' return a.toString() > b.toString() ? 1 : -1; },',
' "IGNORE_CASE": function(a, b) {',
' return a.toString().toLowerCase() > ' +
'b.toString().toLowerCase() ? 1 : -1; },',
' };', ' var compare = compareFuncs[type];',
' return function(a, b) { return compare(a, b) * direction; }', '}'
]);
JavaScript.provideFunction_('listsGetSortCompare', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(type, direction) {
var compareFuncs = {
'NUMERIC': function(a, b) {
return Number(a) - Number(b); },
'TEXT': function(a, b) {
return a.toString() > b.toString() ? 1 : -1; },
'IGNORE_CASE': function(a, b) {
return a.toString().toLowerCase() > b.toString().toLowerCase() ? 1 : -1; },
};
var compare = compareFuncs[type];
return function(a, b) { return compare(a, b) * direction; };
}
`);
return [
list + '.slice().sort(' + getCompareFunctionName + '("' + type + '", ' +
direction + '))',
@@ -368,12 +375,12 @@ JavaScript['lists_split'] = function(block) {
// Block for splitting text into a list, or joining a list into text.
let input = JavaScript.valueToCode(block, 'INPUT', JavaScript.ORDER_MEMBER);
const delimiter =
JavaScript.valueToCode(block, 'DELIM', JavaScript.ORDER_NONE) || '\'\'';
JavaScript.valueToCode(block, 'DELIM', JavaScript.ORDER_NONE) || "''";
const mode = block.getFieldValue('MODE');
let functionName;
if (mode === 'SPLIT') {
if (!input) {
input = '\'\'';
input = "''";
}
functionName = 'split';
} else if (mode === 'JOIN') {

View File

@@ -31,7 +31,7 @@ JavaScript['math_arithmetic'] = function(block) {
'MINUS': [' - ', JavaScript.ORDER_SUBTRACTION],
'MULTIPLY': [' * ', JavaScript.ORDER_MULTIPLICATION],
'DIVIDE': [' / ', JavaScript.ORDER_DIVISION],
'POWER': [null, JavaScript.ORDER_NONE] // Handle power separately.
'POWER': [null, JavaScript.ORDER_NONE], // Handle power separately.
};
const tuple = OPERATORS[block.getFieldValue('OP')];
const operator = tuple[0];
@@ -137,11 +137,10 @@ JavaScript['math_constant'] = function(block) {
const CONSTANTS = {
'PI': ['Math.PI', JavaScript.ORDER_MEMBER],
'E': ['Math.E', JavaScript.ORDER_MEMBER],
'GOLDEN_RATIO':
['(1 + Math.sqrt(5)) / 2', JavaScript.ORDER_DIVISION],
'GOLDEN_RATIO': ['(1 + Math.sqrt(5)) / 2', JavaScript.ORDER_DIVISION],
'SQRT2': ['Math.SQRT2', JavaScript.ORDER_MEMBER],
'SQRT1_2': ['Math.SQRT1_2', JavaScript.ORDER_MEMBER],
'INFINITY': ['Infinity', JavaScript.ORDER_ATOMIC]
'INFINITY': ['Infinity', JavaScript.ORDER_ATOMIC],
};
return CONSTANTS[block.getFieldValue('CONSTANT')];
};
@@ -150,20 +149,16 @@ JavaScript['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 PROPERTIES = {
'EVEN': [' % 2 === 0', JavaScript.ORDER_MODULUS,
JavaScript.ORDER_EQUALITY],
'ODD': [' % 2 === 1', JavaScript.ORDER_MODULUS,
JavaScript.ORDER_EQUALITY],
'EVEN': [' % 2 === 0', JavaScript.ORDER_MODULUS, JavaScript.ORDER_EQUALITY],
'ODD': [' % 2 === 1', JavaScript.ORDER_MODULUS, JavaScript.ORDER_EQUALITY],
'WHOLE': [' % 1 === 0', JavaScript.ORDER_MODULUS,
JavaScript.ORDER_EQUALITY],
'POSITIVE': [' > 0', JavaScript.ORDER_RELATIONAL,
JavaScript.ORDER_RELATIONAL],
'NEGATIVE': [' < 0', JavaScript.ORDER_RELATIONAL,
JavaScript.ORDER_RELATIONAL],
'DIVISIBLE_BY': [null, JavaScript.ORDER_MODULUS,
JavaScript.ORDER_EQUALITY],
'PRIME': [null, JavaScript.ORDER_NONE,
JavaScript.ORDER_FUNCTION_CALL]
'DIVISIBLE_BY': [null, JavaScript.ORDER_MODULUS, JavaScript.ORDER_EQUALITY],
'PRIME': [null, JavaScript.ORDER_NONE, JavaScript.ORDER_FUNCTION_CALL],
};
const dropdownProperty = block.getFieldValue('PROPERTY');
const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty];
@@ -172,27 +167,26 @@ JavaScript['math_number_property'] = function(block) {
let code;
if (dropdownProperty === 'PRIME') {
// Prime is a special case as it is not a one-liner test.
const functionName = JavaScript.provideFunction_(
'mathIsPrime',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ + '(n) {',
' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' if (n == 2 || n == 3) {',
' return true;',
' }',
' // False if n is NaN, negative, is 1, or not whole.',
' // And false if n is divisible by 2 or 3.',
' if (isNaN(n) || 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;',
'}']);
const functionName = JavaScript.provideFunction_('mathIsPrime', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(n) {
// https://en.wikipedia.org/wiki/Primality_test#Naive_methods
if (n == 2 || n == 3) {
return true;
}
// False if n is NaN, negative, is 1, or not whole.
// And false if n is divisible by 2 or 3.
if (isNaN(n) || 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 = JavaScript.valueToCode(block, 'DIVISOR',
@@ -242,13 +236,11 @@ JavaScript['math_on_list'] = function(block) {
break;
case 'AVERAGE': {
// mathMean([null,null,1,3]) === 2.0.
const functionName = JavaScript.provideFunction_(
'mathMean',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(myList) {',
' return myList.reduce(function(x, y) {return x + y;}) / ' +
'myList.length;',
'}']);
const functionName = JavaScript.provideFunction_('mathMean', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(myList) {
return myList.reduce(function(x, y) {return x + y;}) / myList.length;
}
`);
list = JavaScript.valueToCode(block, 'LIST',
JavaScript.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
@@ -256,21 +248,18 @@ JavaScript['math_on_list'] = function(block) {
}
case 'MEDIAN': {
// mathMedian([null,null,1,3]) === 2.0.
const functionName = JavaScript.provideFunction_(
'mathMedian',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(myList) {',
' var localList = myList.filter(function (x) ' +
'{return typeof x === \'number\';});',
' if (!localList.length) return null;',
' localList.sort(function(a, b) {return b - a;});',
' if (localList.length % 2 === 0) {',
' return (localList[localList.length / 2 - 1] + ' +
'localList[localList.length / 2]) / 2;',
' } else {',
' return localList[(localList.length - 1) / 2];',
' }',
'}']);
const functionName = JavaScript.provideFunction_('mathMedian', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(myList) {
var localList = myList.filter(function (x) {return typeof x === \'number\';});
if (!localList.length) return null;
localList.sort(function(a, b) {return b - a;});
if (localList.length % 2 === 0) {
return (localList[localList.length / 2 - 1] + localList[localList.length / 2]) / 2;
} else {
return localList[(localList.length - 1) / 2];
}
}
`);
list = JavaScript.valueToCode(block, 'LIST',
JavaScript.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
@@ -280,70 +269,67 @@ JavaScript['math_on_list'] = function(block) {
// 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 = JavaScript.provideFunction_(
'mathModes',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(values) {',
' var modes = [];',
' var counts = [];',
' var maxCount = 0;',
' for (var i = 0; i < values.length; i++) {',
' var value = values[i];',
' var found = false;',
' var thisCount;',
' for (var j = 0; j < counts.length; j++) {',
' if (counts[j][0] === value) {',
' thisCount = ++counts[j][1];',
' found = true;',
' break;',
' }',
' }',
' if (!found) {',
' counts.push([value, 1]);',
' thisCount = 1;',
' }',
' maxCount = Math.max(thisCount, maxCount);',
' }',
' for (var j = 0; j < counts.length; j++) {',
' if (counts[j][1] === maxCount) {',
' modes.push(counts[j][0]);',
' }',
' }',
' return modes;',
'}']);
const functionName = JavaScript.provideFunction_('mathModes', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(values) {
var modes = [];
var counts = [];
var maxCount = 0;
for (var i = 0; i < values.length; i++) {
var value = values[i];
var found = false;
var thisCount;
for (var j = 0; j < counts.length; j++) {
if (counts[j][0] === value) {
thisCount = ++counts[j][1];
found = true;
break;
}
}
if (!found) {
counts.push([value, 1]);
thisCount = 1;
}
maxCount = Math.max(thisCount, maxCount);
}
for (var j = 0; j < counts.length; j++) {
if (counts[j][1] === maxCount) {
modes.push(counts[j][0]);
}
}
return modes;
}
`);
list = JavaScript.valueToCode(block, 'LIST',
JavaScript.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
break;
}
case 'STD_DEV': {
const functionName = JavaScript.provideFunction_(
'mathStandardDeviation',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(numbers) {',
' var n = numbers.length;',
' if (!n) return null;',
' var mean = numbers.reduce(function(x, y) {return x + y;}) / n;',
' var variance = 0;',
' for (var j = 0; j < n; j++) {',
' variance += Math.pow(numbers[j] - mean, 2);',
' }',
' variance = variance / n;',
' return Math.sqrt(variance);',
'}']);
const functionName = JavaScript.provideFunction_('mathStandardDeviation', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(numbers) {
var n = numbers.length;
if (!n) return null;
var mean = numbers.reduce(function(x, y) {return x + y;}) / n;
var variance = 0;
for (var j = 0; j < n; j++) {
variance += Math.pow(numbers[j] - mean, 2);
}
variance = variance / n;
return Math.sqrt(variance);
}
`);
list = JavaScript.valueToCode(block, 'LIST',
JavaScript.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
break;
}
case 'RANDOM': {
const functionName = JavaScript.provideFunction_(
'mathRandomList',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(list) {',
' var x = Math.floor(Math.random() * list.length);',
' return list[x];',
'}']);
const functionName = JavaScript.provideFunction_('mathRandomList', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(list) {
var x = Math.floor(Math.random() * list.length);
return list[x];
}
`);
list = JavaScript.valueToCode(block, 'LIST',
JavaScript.ORDER_NONE) || '[]';
code = functionName + '(' + list + ')';
@@ -384,18 +370,17 @@ JavaScript['math_random_int'] = function(block) {
JavaScript.ORDER_NONE) || '0';
const argument1 = JavaScript.valueToCode(block, 'TO',
JavaScript.ORDER_NONE) || '0';
const functionName = JavaScript.provideFunction_(
'mathRandomInt',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(a, b) {',
' if (a > b) {',
' // Swap a and b to ensure a is smaller.',
' var c = a;',
' a = b;',
' b = c;',
' }',
' return Math.floor(Math.random() * (b - a + 1) + a);',
'}']);
const functionName = JavaScript.provideFunction_('mathRandomInt', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(a, b) {
if (a > b) {
// Swap a and b to ensure a is smaller.
var c = a;
a = b;
b = c;
}
return Math.floor(Math.random() * (b - a + 1) + a);
}
`);
const code = functionName + '(' + argument0 + ', ' + argument1 + ')';
return [code, JavaScript.ORDER_FUNCTION_CALL];
};

View File

@@ -71,18 +71,18 @@ JavaScript['text_join'] = function(block) {
// Create a string made up of any number of elements of any type.
switch (block.itemCount_) {
case 0:
return ['\'\'', JavaScript.ORDER_ATOMIC];
return ["''", JavaScript.ORDER_ATOMIC];
case 1: {
const element = JavaScript.valueToCode(block, 'ADD0',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const codeAndOrder = forceString(element);
return codeAndOrder;
}
case 2: {
const element0 = JavaScript.valueToCode(block, 'ADD0',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const element1 = JavaScript.valueToCode(block, 'ADD1',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const code = forceString(element0)[0] +
' + ' + forceString(element1)[0];
return [code, JavaScript.ORDER_ADDITION];
@@ -91,7 +91,7 @@ JavaScript['text_join'] = function(block) {
const elements = new Array(block.itemCount_);
for (let i = 0; i < block.itemCount_; i++) {
elements[i] = JavaScript.valueToCode(block, 'ADD' + i,
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
}
const code = '[' + elements.join(',') + '].join(\'\')';
return [code, JavaScript.ORDER_FUNCTION_CALL];
@@ -104,7 +104,7 @@ JavaScript['text_append'] = function(block) {
const varName = JavaScript.nameDB_.getName(
block.getFieldValue('VAR'), NameType.VARIABLE);
const value = JavaScript.valueToCode(block, 'TEXT',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const code = varName + ' += ' +
forceString(value)[0] + ';\n';
return code;
@@ -113,14 +113,14 @@ JavaScript['text_append'] = function(block) {
JavaScript['text_length'] = function(block) {
// String or array length.
const text = JavaScript.valueToCode(block, 'VALUE',
JavaScript.ORDER_MEMBER) || '\'\'';
JavaScript.ORDER_MEMBER) || "''";
return [text + '.length', JavaScript.ORDER_MEMBER];
};
JavaScript['text_isEmpty'] = function(block) {
// Is the string null or array empty?
const text = JavaScript.valueToCode(block, 'VALUE',
JavaScript.ORDER_MEMBER) || '\'\'';
JavaScript.ORDER_MEMBER) || "''";
return ['!' + text + '.length', JavaScript.ORDER_LOGICAL_NOT];
};
@@ -129,9 +129,9 @@ JavaScript['text_indexOf'] = function(block) {
const operator = block.getFieldValue('END') === 'FIRST' ?
'indexOf' : 'lastIndexOf';
const substring = JavaScript.valueToCode(block, 'FIND',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const text = JavaScript.valueToCode(block, 'VALUE',
JavaScript.ORDER_MEMBER) || '\'\'';
JavaScript.ORDER_MEMBER) || "''";
const code = text + '.' + operator + '(' + substring + ')';
// Adjust index if using one-based indices.
if (block.workspace.options.oneBasedIndex) {
@@ -146,8 +146,7 @@ JavaScript['text_charAt'] = function(block) {
const where = block.getFieldValue('WHERE') || 'FROM_START';
const textOrder = (where === 'RANDOM') ? JavaScript.ORDER_NONE :
JavaScript.ORDER_MEMBER;
const text = JavaScript.valueToCode(block, 'VALUE',
textOrder) || '\'\'';
const text = JavaScript.valueToCode(block, 'VALUE', textOrder) || "''";
switch (where) {
case 'FIRST': {
const code = text + '.charAt(0)';
@@ -169,13 +168,12 @@ JavaScript['text_charAt'] = function(block) {
return [code, JavaScript.ORDER_FUNCTION_CALL];
}
case 'RANDOM': {
const functionName = JavaScript.provideFunction_(
'textRandomLetter',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(text) {',
' var x = Math.floor(Math.random() * text.length);',
' return text[x];',
'}']);
const functionName = JavaScript.provideFunction_('textRandomLetter', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(text) {
var x = Math.floor(Math.random() * text.length);
return text[x];
}
`);
const code = functionName + '(' + text + ')';
return [code, JavaScript.ORDER_FUNCTION_CALL];
}
@@ -191,8 +189,7 @@ JavaScript['text_getSubstring'] = function(block) {
where2 !== 'FROM_END' && where2 !== 'LAST');
const textOrder = requiresLengthCall ? JavaScript.ORDER_MEMBER :
JavaScript.ORDER_NONE;
const text = JavaScript.valueToCode(block, 'STRING',
textOrder) || '\'\'';
const text = JavaScript.valueToCode(block, 'STRING', textOrder) || "''";
let code;
if (where1 === 'FIRST' && where2 === 'LAST') {
code = text;
@@ -238,22 +235,20 @@ JavaScript['text_getSubstring'] = function(block) {
const at2 = JavaScript.getAdjusted(block, 'AT2');
const wherePascalCase = {'FIRST': 'First', 'LAST': 'Last',
'FROM_START': 'FromStart', 'FROM_END': 'FromEnd'};
// The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter.
const at1Param =
(where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' : '';
const at2Param =
(where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' : '';
const functionName = JavaScript.provideFunction_(
'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], [
'function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(sequence' +
// The value for 'FROM_END' and'FROM_START' depends on `at` so
// we add it as a parameter.
((where1 === 'FROM_END' || where1 === 'FROM_START') ? ', at1' :
'') +
((where2 === 'FROM_END' || where2 === 'FROM_START') ? ', at2' :
'') +
') {',
' var start = ' + getSubstringIndex('sequence', where1, 'at1') + ';',
' var end = ' + getSubstringIndex('sequence', where2, 'at2') +
' + 1;',
' return sequence.slice(start, end);', '}'
]);
'subsequence' + wherePascalCase[where1] + wherePascalCase[where2], `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(sequence${at1Param}${at2Param}) {
var start = ${getSubstringIndex('sequence', where1, 'at1')};
var end = ${getSubstringIndex('sequence', where2, 'at2')} + 1;
return sequence.slice(start, end);
}
`);
code = functionName + '(' + text +
// The value for 'FROM_END' and 'FROM_START' depends on `at` so we
// pass it.
@@ -269,27 +264,23 @@ JavaScript['text_changeCase'] = function(block) {
const OPERATORS = {
'UPPERCASE': '.toUpperCase()',
'LOWERCASE': '.toLowerCase()',
'TITLECASE': null
'TITLECASE': null,
};
const operator = OPERATORS[block.getFieldValue('CASE')];
const textOrder = operator ? JavaScript.ORDER_MEMBER :
JavaScript.ORDER_NONE;
const text = JavaScript.valueToCode(block, 'TEXT',
textOrder) || '\'\'';
const textOrder = operator ? JavaScript.ORDER_MEMBER : JavaScript.ORDER_NONE;
const text = JavaScript.valueToCode(block, 'TEXT', textOrder) || "''";
let code;
if (operator) {
// Upper and lower case are functions built into JavaScript.
code = text + operator;
} else {
// Title case is not a native JavaScript function. Define one.
const functionName = JavaScript.provideFunction_(
'textToTitleCase',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(str) {',
' return str.replace(/\\S+/g,',
' function(txt) {return txt[0].toUpperCase() + ' +
'txt.substring(1).toLowerCase();});',
'}']);
const functionName = JavaScript.provideFunction_('textToTitleCase', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(str) {
return str.replace(/\\S+/g,
function(txt) {return txt[0].toUpperCase() + txt.substring(1).toLowerCase();});
}
`);
code = functionName + '(' + text + ')';
}
return [code, JavaScript.ORDER_FUNCTION_CALL];
@@ -300,18 +291,18 @@ JavaScript['text_trim'] = function(block) {
const OPERATORS = {
'LEFT': ".replace(/^[\\s\\xa0]+/, '')",
'RIGHT': ".replace(/[\\s\\xa0]+$/, '')",
'BOTH': '.trim()'
'BOTH': '.trim()',
};
const operator = OPERATORS[block.getFieldValue('MODE')];
const text = JavaScript.valueToCode(block, 'TEXT',
JavaScript.ORDER_MEMBER) || '\'\'';
JavaScript.ORDER_MEMBER) || "''";
return [text + operator, JavaScript.ORDER_FUNCTION_CALL];
};
JavaScript['text_print'] = function(block) {
// Print statement.
const msg = JavaScript.valueToCode(block, 'TEXT',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
return 'window.alert(' + msg + ');\n';
};
@@ -323,8 +314,7 @@ JavaScript['text_prompt_ext'] = function(block) {
msg = JavaScript.quote_(block.getFieldValue('TEXT'));
} else {
// External message.
msg = JavaScript.valueToCode(block, 'TEXT',
JavaScript.ORDER_NONE) || '\'\'';
msg = JavaScript.valueToCode(block, 'TEXT', JavaScript.ORDER_NONE) || "''";
}
let code = 'window.prompt(' + msg + ')';
const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
@@ -338,48 +328,44 @@ JavaScript['text_prompt'] = JavaScript['text_prompt_ext'];
JavaScript['text_count'] = function(block) {
const text = JavaScript.valueToCode(block, 'TEXT',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const sub = JavaScript.valueToCode(block, 'SUB',
JavaScript.ORDER_NONE) || '\'\'';
const functionName = JavaScript.provideFunction_(
'textCount',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(haystack, needle) {',
' if (needle.length === 0) {',
' return haystack.length + 1;',
' } else {',
' return haystack.split(needle).length - 1;',
' }',
'}']);
JavaScript.ORDER_NONE) || "''";
const functionName = JavaScript.provideFunction_('textCount', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle) {
if (needle.length === 0) {
return haystack.length + 1;
} else {
return haystack.split(needle).length - 1;
}
}
`);
const code = functionName + '(' + text + ', ' + sub + ')';
return [code, JavaScript.ORDER_FUNCTION_CALL];
};
JavaScript['text_replace'] = function(block) {
const text = JavaScript.valueToCode(block, 'TEXT',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const from = JavaScript.valueToCode(block, 'FROM',
JavaScript.ORDER_NONE) || '\'\'';
const to = JavaScript.valueToCode(block, 'TO',
JavaScript.ORDER_NONE) || '\'\'';
JavaScript.ORDER_NONE) || "''";
const to = JavaScript.valueToCode(block, 'TO', JavaScript.ORDER_NONE) || "''";
// The regex escaping code below is taken from the implementation of
// goog.string.regExpEscape.
const functionName = JavaScript.provideFunction_(
'textReplace',
['function ' + JavaScript.FUNCTION_NAME_PLACEHOLDER_ +
'(haystack, needle, replacement) {',
' needle = ' +
'needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g,"\\\\$1")',
' .replace(/\\x08/g,"\\\\x08");',
' return haystack.replace(new RegExp(needle, \'g\'), replacement);',
'}']);
const functionName = JavaScript.provideFunction_('textReplace', `
function ${JavaScript.FUNCTION_NAME_PLACEHOLDER_}(haystack, needle, replacement) {
needle = needle.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')
.replace(/\\x08/g, '\\\\x08');
return haystack.replace(new RegExp(needle, \'g\'), replacement);
}
`);
const code = functionName + '(' + text + ', ' + from + ', ' + to + ')';
return [code, JavaScript.ORDER_FUNCTION_CALL];
};
JavaScript['text_reverse'] = function(block) {
const text = JavaScript.valueToCode(block, 'TEXT',
JavaScript.ORDER_MEMBER) || '\'\'';
const code = text + '.split(\'\').reverse().join(\'\')';
JavaScript.ORDER_MEMBER) || "''";
const code = text + ".split('').reverse().join('')";
return [code, JavaScript.ORDER_FUNCTION_CALL];
};