math.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2015 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Generating PHP for math blocks.
  22. * @author daarond@gmail.com (Daaron Dwyer)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.PHP.math');
  26. goog.require('Blockly.PHP');
  27. Blockly.PHP['math_number'] = function(block) {
  28. // Numeric value.
  29. var code = parseFloat(block.getFieldValue('NUM'));
  30. if (code == Infinity) {
  31. code = 'INF';
  32. } else if (code == -Infinity) {
  33. code = '-INF';
  34. }
  35. return [code, Blockly.PHP.ORDER_ATOMIC];
  36. };
  37. Blockly.PHP['math_arithmetic'] = function(block) {
  38. // Basic arithmetic operators, and power.
  39. var OPERATORS = {
  40. 'ADD': [' + ', Blockly.PHP.ORDER_ADDITION],
  41. 'MINUS': [' - ', Blockly.PHP.ORDER_SUBTRACTION],
  42. 'MULTIPLY': [' * ', Blockly.PHP.ORDER_MULTIPLICATION],
  43. 'DIVIDE': [' / ', Blockly.PHP.ORDER_DIVISION],
  44. 'POWER': [null, Blockly.PHP.ORDER_COMMA] // Handle power separately.
  45. };
  46. var tuple = OPERATORS[block.getFieldValue('OP')];
  47. var operator = tuple[0];
  48. var order = tuple[1];
  49. var argument0 = Blockly.PHP.valueToCode(block, 'A', order) || '0';
  50. var argument1 = Blockly.PHP.valueToCode(block, 'B', order) || '0';
  51. var code;
  52. // Power in PHP requires a special case since it has no operator.
  53. if (!operator) {
  54. code = 'pow(' + argument0 + ', ' + argument1 + ')';
  55. return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
  56. }
  57. code = argument0 + operator + argument1;
  58. return [code, order];
  59. };
  60. Blockly.PHP['math_single'] = function(block) {
  61. // Math operators with single operand.
  62. var operator = block.getFieldValue('OP');
  63. var code;
  64. var arg;
  65. if (operator == 'NEG') {
  66. // Negation is a special case given its different operator precedence.
  67. arg = Blockly.PHP.valueToCode(block, 'NUM',
  68. Blockly.PHP.ORDER_UNARY_NEGATION) || '0';
  69. if (arg[0] == '-') {
  70. // --3 is not legal in JS.
  71. arg = ' ' + arg;
  72. }
  73. code = '-' + arg;
  74. return [code, Blockly.PHP.ORDER_UNARY_NEGATION];
  75. }
  76. if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
  77. arg = Blockly.PHP.valueToCode(block, 'NUM',
  78. Blockly.PHP.ORDER_DIVISION) || '0';
  79. } else {
  80. arg = Blockly.PHP.valueToCode(block, 'NUM',
  81. Blockly.PHP.ORDER_NONE) || '0';
  82. }
  83. // First, handle cases which generate values that don't need parentheses
  84. // wrapping the code.
  85. switch (operator) {
  86. case 'ABS':
  87. code = 'abs(' + arg + ')';
  88. break;
  89. case 'ROOT':
  90. code = 'sqrt(' + arg + ')';
  91. break;
  92. case 'LN':
  93. code = 'log(' + arg + ')';
  94. break;
  95. case 'EXP':
  96. code = 'exp(' + arg + ')';
  97. break;
  98. case 'POW10':
  99. code = 'pow(10,' + arg + ')';
  100. break;
  101. case 'ROUND':
  102. code = 'round(' + arg + ')';
  103. break;
  104. case 'ROUNDUP':
  105. code = 'ceil(' + arg + ')';
  106. break;
  107. case 'ROUNDDOWN':
  108. code = 'floor(' + arg + ')';
  109. break;
  110. case 'SIN':
  111. code = 'sin(' + arg + ' / 180 * pi())';
  112. break;
  113. case 'COS':
  114. code = 'cos(' + arg + ' / 180 * pi())';
  115. break;
  116. case 'TAN':
  117. code = 'tan(' + arg + ' / 180 * pi())';
  118. break;
  119. }
  120. if (code) {
  121. return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
  122. }
  123. // Second, handle cases which generate values that may need parentheses
  124. // wrapping the code.
  125. switch (operator) {
  126. case 'LOG10':
  127. code = 'log(' + arg + ') / log(10)';
  128. break;
  129. case 'ASIN':
  130. code = 'asin(' + arg + ') / pi() * 180';
  131. break;
  132. case 'ACOS':
  133. code = 'acos(' + arg + ') / pi() * 180';
  134. break;
  135. case 'ATAN':
  136. code = 'atan(' + arg + ') / pi() * 180';
  137. break;
  138. default:
  139. throw 'Unknown math operator: ' + operator;
  140. }
  141. return [code, Blockly.PHP.ORDER_DIVISION];
  142. };
  143. Blockly.PHP['math_constant'] = function(block) {
  144. // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
  145. var CONSTANTS = {
  146. 'PI': ['M_PI', Blockly.PHP.ORDER_ATOMIC],
  147. 'E': ['M_E', Blockly.PHP.ORDER_ATOMIC],
  148. 'GOLDEN_RATIO': ['(1 + sqrt(5)) / 2', Blockly.PHP.ORDER_DIVISION],
  149. 'SQRT2': ['M_SQRT2', Blockly.PHP.ORDER_ATOMIC],
  150. 'SQRT1_2': ['M_SQRT1_2', Blockly.PHP.ORDER_ATOMIC],
  151. 'INFINITY': ['INF', Blockly.PHP.ORDER_ATOMIC]
  152. };
  153. return CONSTANTS[block.getFieldValue('CONSTANT')];
  154. };
  155. Blockly.PHP['math_number_property'] = function(block) {
  156. // Check if a number is even, odd, prime, whole, positive, or negative
  157. // or if it is divisible by certain number. Returns true or false.
  158. var number_to_check = Blockly.PHP.valueToCode(block, 'NUMBER_TO_CHECK',
  159. Blockly.PHP.ORDER_MODULUS) || '0';
  160. var dropdown_property = block.getFieldValue('PROPERTY');
  161. var code;
  162. if (dropdown_property == 'PRIME') {
  163. // Prime is a special case as it is not a one-liner test.
  164. var functionName = Blockly.PHP.provideFunction_(
  165. 'math_isPrime',
  166. [ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ + '($n) {',
  167. ' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods',
  168. ' if ($n == 2 || $n == 3) {',
  169. ' return true;',
  170. ' }',
  171. ' // False if n is NaN, negative, is 1, or not whole.',
  172. ' // And false if n is divisible by 2 or 3.',
  173. ' if (!is_numeric($n) || $n <= 1 || $n % 1 != 0 || $n % 2 == 0 ||' +
  174. ' $n % 3 == 0) {',
  175. ' return false;',
  176. ' }',
  177. ' // Check all the numbers of form 6k +/- 1, up to sqrt(n).',
  178. ' for ($x = 6; $x <= sqrt($n) + 1; $x += 6) {',
  179. ' if ($n % ($x - 1) == 0 || $n % ($x + 1) == 0) {',
  180. ' return false;',
  181. ' }',
  182. ' }',
  183. ' return true;',
  184. '}']);
  185. code = functionName + '(' + number_to_check + ')';
  186. return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
  187. }
  188. switch (dropdown_property) {
  189. case 'EVEN':
  190. code = number_to_check + ' % 2 == 0';
  191. break;
  192. case 'ODD':
  193. code = number_to_check + ' % 2 == 1';
  194. break;
  195. case 'WHOLE':
  196. code = 'is_int(' + number_to_check + ')';
  197. break;
  198. case 'POSITIVE':
  199. code = number_to_check + ' > 0';
  200. break;
  201. case 'NEGATIVE':
  202. code = number_to_check + ' < 0';
  203. break;
  204. case 'DIVISIBLE_BY':
  205. var divisor = Blockly.PHP.valueToCode(block, 'DIVISOR',
  206. Blockly.PHP.ORDER_MODULUS) || '0';
  207. code = number_to_check + ' % ' + divisor + ' == 0';
  208. break;
  209. }
  210. return [code, Blockly.PHP.ORDER_EQUALITY];
  211. };
  212. Blockly.PHP['math_change'] = function(block) {
  213. // Add to a variable in place.
  214. var argument0 = Blockly.PHP.valueToCode(block, 'DELTA',
  215. Blockly.PHP.ORDER_ADDITION) || '0';
  216. var varName = Blockly.PHP.variableDB_.getName(
  217. block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  218. return varName + ' += ' + argument0 + ';\n';
  219. };
  220. // Rounding functions have a single operand.
  221. Blockly.PHP['math_round'] = Blockly.PHP['math_single'];
  222. // Trigonometry functions have a single operand.
  223. Blockly.PHP['math_trig'] = Blockly.PHP['math_single'];
  224. Blockly.PHP['math_on_list'] = function(block) {
  225. // Math functions for lists.
  226. var func = block.getFieldValue('OP');
  227. var list, code;
  228. switch (func) {
  229. case 'SUM':
  230. list = Blockly.PHP.valueToCode(block, 'LIST',
  231. Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
  232. code = 'array_sum(' + list + ')';
  233. break;
  234. case 'MIN':
  235. list = Blockly.PHP.valueToCode(block, 'LIST',
  236. Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
  237. code = 'min(' + list + ')';
  238. break;
  239. case 'MAX':
  240. list = Blockly.PHP.valueToCode(block, 'LIST',
  241. Blockly.PHP.ORDER_FUNCTION_CALL) || 'array()';
  242. code = 'max(' + list + ')';
  243. break;
  244. case 'AVERAGE':
  245. var functionName = Blockly.PHP.provideFunction_(
  246. 'math_mean',
  247. [ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
  248. '($myList) {',
  249. ' return array_sum($myList) / count($myList);',
  250. '}']);
  251. list = Blockly.PHP.valueToCode(block, 'LIST',
  252. Blockly.PHP.ORDER_NONE) || 'array()';
  253. code = functionName + '(' + list + ')';
  254. break;
  255. case 'MEDIAN':
  256. var functionName = Blockly.PHP.provideFunction_(
  257. 'math_median',
  258. [ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
  259. '($arr) {',
  260. ' sort($arr,SORT_NUMERIC);',
  261. ' return (count($arr) % 2) ? $arr[floor(count($arr)/2)] : ',
  262. ' ($arr[floor(count($arr)/2)] + $arr[floor(count($arr)/2) - 1]) / 2;',
  263. '}']);
  264. list = Blockly.PHP.valueToCode(block, 'LIST',
  265. Blockly.PHP.ORDER_NONE) || '[]';
  266. code = functionName + '(' + list + ')';
  267. break;
  268. case 'MODE':
  269. // As a list of numbers can contain more than one mode,
  270. // the returned result is provided as an array.
  271. // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
  272. var functionName = Blockly.PHP.provideFunction_(
  273. 'math_modes',
  274. [ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
  275. '($values) {',
  276. ' $v = array_count_values($values);',
  277. ' arsort($v);',
  278. ' foreach($v as $k => $v){$total = $k; break;}',
  279. ' return array($total);',
  280. '}']);
  281. list = Blockly.PHP.valueToCode(block, 'LIST',
  282. Blockly.PHP.ORDER_NONE) || '[]';
  283. code = functionName + '(' + list + ')';
  284. break;
  285. case 'STD_DEV':
  286. var functionName = Blockly.PHP.provideFunction_(
  287. 'math_standard_deviation',
  288. [ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
  289. '($numbers) {',
  290. ' $n = count($numbers);',
  291. ' if (!$n) return null;',
  292. ' $mean = array_sum($numbers) / count($numbers);',
  293. ' foreach($numbers as $key => $num) $devs[$key] = pow($num - $mean, 2);',
  294. ' return sqrt(array_sum($devs) / (count($devs) - 1));',
  295. '}']);
  296. list = Blockly.PHP.valueToCode(block, 'LIST',
  297. Blockly.PHP.ORDER_NONE) || '[]';
  298. code = functionName + '(' + list + ')';
  299. break;
  300. case 'RANDOM':
  301. var functionName = Blockly.PHP.provideFunction_(
  302. 'math_random_list',
  303. [ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
  304. '($list) {',
  305. ' $x = rand(0, count($list)-1);',
  306. ' return $list[$x];',
  307. '}']);
  308. list = Blockly.PHP.valueToCode(block, 'LIST',
  309. Blockly.PHP.ORDER_NONE) || '[]';
  310. code = functionName + '(' + list + ')';
  311. break;
  312. default:
  313. throw 'Unknown operator: ' + func;
  314. }
  315. return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
  316. };
  317. Blockly.PHP['math_modulo'] = function(block) {
  318. // Remainder computation.
  319. var argument0 = Blockly.PHP.valueToCode(block, 'DIVIDEND',
  320. Blockly.PHP.ORDER_MODULUS) || '0';
  321. var argument1 = Blockly.PHP.valueToCode(block, 'DIVISOR',
  322. Blockly.PHP.ORDER_MODULUS) || '0';
  323. var code = argument0 + ' % ' + argument1;
  324. return [code, Blockly.PHP.ORDER_MODULUS];
  325. };
  326. Blockly.PHP['math_constrain'] = function(block) {
  327. // Constrain a number between two limits.
  328. var argument0 = Blockly.PHP.valueToCode(block, 'VALUE',
  329. Blockly.PHP.ORDER_COMMA) || '0';
  330. var argument1 = Blockly.PHP.valueToCode(block, 'LOW',
  331. Blockly.PHP.ORDER_COMMA) || '0';
  332. var argument2 = Blockly.PHP.valueToCode(block, 'HIGH',
  333. Blockly.PHP.ORDER_COMMA) || 'Infinity';
  334. var code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
  335. argument2 + ')';
  336. return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
  337. };
  338. Blockly.PHP['math_random_int'] = function(block) {
  339. // Random integer between [X] and [Y].
  340. var argument0 = Blockly.PHP.valueToCode(block, 'FROM',
  341. Blockly.PHP.ORDER_COMMA) || '0';
  342. var argument1 = Blockly.PHP.valueToCode(block, 'TO',
  343. Blockly.PHP.ORDER_COMMA) || '0';
  344. var functionName = Blockly.PHP.provideFunction_(
  345. 'math_random_int',
  346. [ 'function ' + Blockly.PHP.FUNCTION_NAME_PLACEHOLDER_ +
  347. '($a, $b) {',
  348. ' if ($a > $b) {',
  349. ' return rand($b, $a);',
  350. ' }',
  351. ' return rand($a, $b);',
  352. '}']);
  353. var code = functionName + '(' + argument0 + ', ' + argument1 + ')';
  354. return [code, Blockly.PHP.ORDER_FUNCTION_CALL];
  355. };
  356. Blockly.PHP['math_random_float'] = function(block) {
  357. // Random fraction between 0 and 1.
  358. return ['(float)rand()/(float)getrandmax()', Blockly.PHP.ORDER_FUNCTION_CALL];
  359. };