print.js 2.7 KB

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