PageRenderTime 38ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/function/utils/format.js

https://github.com/mpmedia/mathjs
JavaScript | 67 lines | 40 code | 6 blank | 21 comment | 17 complexity | 74d8463545b6624e926c7776a73738fa MD5 | raw file
Possible License(s): Apache-2.0
  1. /**
  2. * Format a value of any type into a string. Interpolate values into the string.
  3. * Numbers are rounded off to a maximum number of 5 digits by default.
  4. * Usage:
  5. * math.format(value)
  6. * math.format(template, object)
  7. *
  8. * Example usage:
  9. * math.format(2/7); // '0.28571'
  10. * math.format(new Complex(2, 3)); // '2 + 3i'
  11. * math.format('Hello $name! The date is $date', {
  12. * name: 'user',
  13. * date: new Date().toISOString().substring(0, 10)
  14. * }); // 'hello user! The date is 2013-03-23'
  15. *
  16. * @param {String} template
  17. * @param {Object} values
  18. * @return {String} str
  19. */
  20. math.format = function format(template, values) {
  21. var num = arguments.length;
  22. if (num != 1 && num != 2) {
  23. throw newArgumentsError('format', num, 1, 2);
  24. }
  25. if (num == 1) {
  26. // just format a value as string
  27. var value = arguments[0];
  28. if (isNumber(value)) {
  29. return util.formatNumber(value, math.options.precision);
  30. }
  31. if (value instanceof Array) {
  32. return util.formatArray(value);
  33. }
  34. if (isString(value)) {
  35. return '"' + value + '"';
  36. }
  37. if (value instanceof Object) {
  38. return value.toString();
  39. }
  40. return String(value);
  41. }
  42. else {
  43. if (!isString(template)) {
  44. throw new TypeError('String expected as first parameter in function format');
  45. }
  46. if (!(values instanceof Object)) {
  47. throw new TypeError('Object expected as first parameter in function format');
  48. }
  49. // format values into a string
  50. return template.replace(/\$([\w\.]+)/g, function (original, key) {
  51. var keys = key.split('.');
  52. var value = values[keys.shift()];
  53. while (keys.length && value != undefined) {
  54. var k = keys.shift();
  55. value = k ? value[k] : value + '.';
  56. }
  57. return value != undefined ? value : original;
  58. }
  59. );
  60. }
  61. };