print.js (2780B)
1 import { format } from '../../utils/string.js'; 2 import { isString } from '../../utils/is.js'; 3 import { factory } from '../../utils/factory.js'; 4 var name = 'print'; 5 var dependencies = ['typed']; 6 export var createPrint = /* #__PURE__ */factory(name, dependencies, _ref => { 7 var { 8 typed 9 } = _ref; 10 11 /** 12 * Interpolate values into a string template. 13 * 14 * Syntax: 15 * 16 * math.print(template, values) 17 * math.print(template, values, precision) 18 * math.print(template, values, options) 19 * 20 * Example usage: 21 * 22 * // the following outputs: 'Lucy is 5 years old' 23 * math.print('Lucy is $age years old', {age: 5}) 24 * 25 * // the following outputs: 'The value of pi is 3.141592654' 26 * math.print('The value of pi is $pi', {pi: math.pi}, 10) 27 * 28 * // the following outputs: 'hello Mary! The date is 2013-03-23' 29 * math.print('Hello $user.name! The date is $date', { 30 * user: { 31 * name: 'Mary', 32 * }, 33 * date: new Date(2013, 2, 23).toISOString().substring(0, 10) 34 * }) 35 * 36 * // the following outputs: 'My favorite fruits are apples and bananas !' 37 * math.print('My favorite fruits are $0 and $1 !', [ 38 * 'apples', 39 * 'bananas' 40 * ]) 41 * 42 * See also: 43 * 44 * format 45 * 46 * @param {string} template A string containing variable placeholders. 47 * @param {Object | Array | Matrix} values An object or array containing variables 48 * which will be filled in in the template. 49 * @param {number | Object} [options] Formatting options, 50 * or the number of digits to format numbers. 51 * See function math.format for a description 52 * of all options. 53 * @return {string} Interpolated string 54 */ 55 return typed(name, { 56 // note: Matrix will be converted automatically to an Array 57 'string, Object | Array': _print, 58 'string, Object | Array, number | Object': _print 59 }); 60 }); 61 /** 62 * Interpolate values into a string template. 63 * @param {string} template 64 * @param {Object} values 65 * @param {number | Object} [options] 66 * @returns {string} Interpolated string 67 * @private 68 */ 69 70 function _print(template, values, options) { 71 return template.replace(/\$([\w.]+)/g, function (original, key) { 72 var keys = key.split('.'); 73 var value = values[keys.shift()]; 74 75 while (keys.length && value !== undefined) { 76 var k = keys.shift(); 77 value = k ? value[k] : value + '.'; 78 } 79 80 if (value !== undefined) { 81 if (!isString(value)) { 82 return format(value, options); 83 } else { 84 return value; 85 } 86 } 87 88 return original; 89 }); 90 }