string.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.compareText = compareText;
  7. exports.endsWith = endsWith;
  8. exports.escape = escape;
  9. exports.format = format;
  10. exports.stringify = stringify;
  11. var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
  12. var _is = require("./is.js");
  13. var _number = require("./number.js");
  14. var _formatter = require("./bignumber/formatter.js");
  15. /**
  16. * Check if a text ends with a certain string.
  17. * @param {string} text
  18. * @param {string} search
  19. */
  20. function endsWith(text, search) {
  21. var start = text.length - search.length;
  22. var end = text.length;
  23. return text.substring(start, end) === search;
  24. }
  25. /**
  26. * Format a value of any type into a string.
  27. *
  28. * Usage:
  29. * math.format(value)
  30. * math.format(value, precision)
  31. * math.format(value, options)
  32. *
  33. * When value is a function:
  34. *
  35. * - When the function has a property `syntax`, it returns this
  36. * syntax description.
  37. * - In other cases, a string `'function'` is returned.
  38. *
  39. * When `value` is an Object:
  40. *
  41. * - When the object contains a property `format` being a function, this
  42. * function is invoked as `value.format(options)` and the result is returned.
  43. * - When the object has its own `toString` method, this method is invoked
  44. * and the result is returned.
  45. * - In other cases the function will loop over all object properties and
  46. * return JSON object notation like '{"a": 2, "b": 3}'.
  47. *
  48. * Example usage:
  49. * math.format(2/7) // '0.2857142857142857'
  50. * math.format(math.pi, 3) // '3.14'
  51. * math.format(new Complex(2, 3)) // '2 + 3i'
  52. * math.format('hello') // '"hello"'
  53. *
  54. * @param {*} value Value to be stringified
  55. * @param {Object | number | Function} [options]
  56. * Formatting options. See src/utils/number.js:format for a
  57. * description of the available options controlling number output.
  58. * This generic "format" also supports the option property `truncate: NN`
  59. * giving the maximum number NN of characters to return (if there would
  60. * have been more, they are deleted and replaced by an ellipsis).
  61. * @return {string} str
  62. */
  63. function format(value, options) {
  64. var result = _format(value, options);
  65. if (options && (0, _typeof2["default"])(options) === 'object' && 'truncate' in options && result.length > options.truncate) {
  66. return result.substring(0, options.truncate - 3) + '...';
  67. }
  68. return result;
  69. }
  70. function _format(value, options) {
  71. if (typeof value === 'number') {
  72. return (0, _number.format)(value, options);
  73. }
  74. if ((0, _is.isBigNumber)(value)) {
  75. return (0, _formatter.format)(value, options);
  76. }
  77. // note: we use unsafe duck-typing here to check for Fractions, this is
  78. // ok here since we're only invoking toString or concatenating its values
  79. if (looksLikeFraction(value)) {
  80. if (!options || options.fraction !== 'decimal') {
  81. // output as ratio, like '1/3'
  82. return value.s * value.n + '/' + value.d;
  83. } else {
  84. // output as decimal, like '0.(3)'
  85. return value.toString();
  86. }
  87. }
  88. if (Array.isArray(value)) {
  89. return formatArray(value, options);
  90. }
  91. if ((0, _is.isString)(value)) {
  92. return '"' + value + '"';
  93. }
  94. if (typeof value === 'function') {
  95. return value.syntax ? String(value.syntax) : 'function';
  96. }
  97. if (value && (0, _typeof2["default"])(value) === 'object') {
  98. if (typeof value.format === 'function') {
  99. return value.format(options);
  100. } else if (value && value.toString(options) !== {}.toString()) {
  101. // this object has a non-native toString method, use that one
  102. return value.toString(options);
  103. } else {
  104. var entries = Object.keys(value).map(function (key) {
  105. return '"' + key + '": ' + format(value[key], options);
  106. });
  107. return '{' + entries.join(', ') + '}';
  108. }
  109. }
  110. return String(value);
  111. }
  112. /**
  113. * Stringify a value into a string enclosed in double quotes.
  114. * Unescaped double quotes and backslashes inside the value are escaped.
  115. * @param {*} value
  116. * @return {string}
  117. */
  118. function stringify(value) {
  119. var text = String(value);
  120. var escaped = '';
  121. var i = 0;
  122. while (i < text.length) {
  123. var c = text.charAt(i);
  124. if (c === '\\') {
  125. escaped += c;
  126. i++;
  127. c = text.charAt(i);
  128. if (c === '' || '"\\/bfnrtu'.indexOf(c) === -1) {
  129. escaped += '\\'; // no valid escape character -> escape it
  130. }
  131. escaped += c;
  132. } else if (c === '"') {
  133. escaped += '\\"';
  134. } else {
  135. escaped += c;
  136. }
  137. i++;
  138. }
  139. return '"' + escaped + '"';
  140. }
  141. /**
  142. * Escape special HTML characters
  143. * @param {*} value
  144. * @return {string}
  145. */
  146. function escape(value) {
  147. var text = String(value);
  148. text = text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  149. return text;
  150. }
  151. /**
  152. * Recursively format an n-dimensional matrix
  153. * Example output: "[[1, 2], [3, 4]]"
  154. * @param {Array} array
  155. * @param {Object | number | Function} [options] Formatting options. See
  156. * lib/utils/number:format for a
  157. * description of the available
  158. * options.
  159. * @returns {string} str
  160. */
  161. function formatArray(array, options) {
  162. if (Array.isArray(array)) {
  163. var str = '[';
  164. var len = array.length;
  165. for (var i = 0; i < len; i++) {
  166. if (i !== 0) {
  167. str += ', ';
  168. }
  169. str += formatArray(array[i], options);
  170. }
  171. str += ']';
  172. return str;
  173. } else {
  174. return format(array, options);
  175. }
  176. }
  177. /**
  178. * Check whether a value looks like a Fraction (unsafe duck-type check)
  179. * @param {*} value
  180. * @return {boolean}
  181. */
  182. function looksLikeFraction(value) {
  183. return value && (0, _typeof2["default"])(value) === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false;
  184. }
  185. /**
  186. * Compare two strings
  187. * @param {string} x
  188. * @param {string} y
  189. * @returns {number}
  190. */
  191. function compareText(x, y) {
  192. // we don't want to convert numbers to string, only accept string input
  193. if (!(0, _is.isString)(x)) {
  194. throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + (0, _is.typeOf)(x) + ', index: 0)');
  195. }
  196. if (!(0, _is.isString)(y)) {
  197. throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + (0, _is.typeOf)(y) + ', index: 1)');
  198. }
  199. return x === y ? 0 : x > y ? 1 : -1;
  200. }