import.js (2547B)
1 /** 2 * Math.js can easily be extended with functions and variables using the 3 * `import` function. The function `import` accepts a module name or an object 4 * containing functions and variables. 5 */ 6 7 // load math.js (using node.js) 8 const { create, all } = require('..') 9 const math = create(all) 10 11 /** 12 * Define new functions and variables 13 */ 14 math.import({ 15 myConstant: 42, 16 hello: function (name) { 17 return 'hello, ' + name + '!' 18 } 19 }) 20 21 // defined methods can be used in both JavaScript as well as the parser 22 print(math.myConstant * 2) // 84 23 print(math.hello('user')) // 'hello, user!' 24 25 print(math.evaluate('myConstant + 10')) // 52 26 print(math.evaluate('hello("user")')) // 'hello, user!' 27 28 /** 29 * Import the math library numbers.js, https://github.com/sjkaliski/numbers.js 30 * The library must be installed first using npm: 31 * npm install numbers 32 */ 33 try { 34 // load the numbers.js library 35 const numbers = require('numbers') 36 37 // import the numbers.js library into math.js 38 math.import(numbers, { wrap: true, silent: true }) 39 40 if (math.fibonacci) { 41 // calculate fibonacci 42 print(math.fibonacci(7)) // 13 43 print(math.evaluate('fibonacci(7)')) // 13 44 } 45 } catch (err) { 46 console.log('Warning: To use numbers.js, the library must ' + 47 'be installed first via `npm install numbers`.') 48 } 49 50 /** 51 * Import the math library numeric.js, https://github.com/sloisel/numeric 52 * The library must be installed first using npm: 53 * npm install numeric 54 */ 55 try { 56 // load the numeric.js library 57 const numeric = require('numeric') 58 59 // import the numeric.js library into math.js 60 math.import(numeric, { wrap: true, silent: true }) 61 62 if (math.eig) { 63 // calculate eigenvalues of a matrix 64 print(math.evaluate('eig([1, 2; 4, 3])').lambda.x) // [5, -1] 65 66 // solve AX = b 67 const A = math.evaluate('[1, 2, 3; 2, -1, 1; 3, 0, -1]') 68 const b = [9, 8, 3] 69 print(math.solve(A, b)) // [2, -1, 3] 70 } 71 } catch (err) { 72 console.log('Warning: To use numeric.js, the library must ' + 73 'be installed first via `npm install numeric`.') 74 } 75 76 /** 77 * By default, the function import does not allow overriding existing functions. 78 * Existing functions can be overridden by specifying option `override: true` 79 */ 80 math.import({ 81 pi: 3.14 82 }, { 83 override: true 84 }) 85 86 print(math.pi) // returns 3.14 instead of 3.141592653589793 87 88 /** 89 * Helper function to output a value in the console. Value will be formatted. 90 * @param {*} value 91 */ 92 function print (value) { 93 const precision = 14 94 console.log(math.format(value, precision)) 95 }