mathjs/src/utils/string.js
Jos de Jong 6f00715754
Specify import require paths (continuation of #1941) (#1962)
* Add `.js` extension to source file imports

* Specify package `exports` in `package.json`

Specify package type as `commonjs` (It's good to be specific)

* Move all compiled scripts into `lib` directory

Remove ./number.js (You can use the compiled ones in `./lib/*`)

Tell node that the `esm` directory is type `module` and enable tree shaking.

Remove unused files from packages `files` property

* Allow importing of package.json

* Make library ESM first

* - Fix merge conflicts
- Refactor `bundleAny` into `defaultInstance.js` and `browserBundle.cjs`
- Refactor unit tests to be able to run with plain nodejs (no transpiling)
- Fix browser examples

* Fix browser and browserstack tests

* Fix running unit tests on Node 10 (which has no support for modules)

* Fix node.js examples (those are still commonjs)

* Remove the need for `browserBundle.cjs`

* Generate minified bundle only

* [Security] Bump node-fetch from 2.6.0 to 2.6.1 (#1963)

Bumps [node-fetch](https://github.com/bitinn/node-fetch) from 2.6.0 to 2.6.1. **This update includes a security fix.**
- [Release notes](https://github.com/bitinn/node-fetch/releases)
- [Changelog](https://github.com/node-fetch/node-fetch/blob/master/docs/CHANGELOG.md)
- [Commits](https://github.com/bitinn/node-fetch/compare/v2.6.0...v2.6.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>

* Cleanup console.log

* Add integration tests to test the entry points (commonjs/esm, full/number only)

* Create backward compatibility error messages in the files moved/removed since v8

* Describe breaking changes in HISTORY.md

* Bump karma from 5.2.1 to 5.2.2 (#1965)

Bumps [karma](https://github.com/karma-runner/karma) from 5.2.1 to 5.2.2.
- [Release notes](https://github.com/karma-runner/karma/releases)
- [Changelog](https://github.com/karma-runner/karma/blob/master/CHANGELOG.md)
- [Commits](https://github.com/karma-runner/karma/compare/v5.2.1...v5.2.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>

Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>

Co-authored-by: Lee Langley-Rees <lee@greenimp.co.uk>
Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
2020-09-20 18:01:29 +02:00

212 lines
5.8 KiB
JavaScript

import { isBigNumber, isString, typeOf } from './is.js'
import { format as formatNumber } from './number.js'
import { format as formatBigNumber } from './bignumber/formatter.js'
/**
* Check if a text ends with a certain string.
* @param {string} text
* @param {string} search
*/
export function endsWith (text, search) {
const start = text.length - search.length
const end = text.length
return (text.substring(start, end) === search)
}
/**
* Format a value of any type into a string.
*
* Usage:
* math.format(value)
* math.format(value, precision)
*
* When value is a function:
*
* - When the function has a property `syntax`, it returns this
* syntax description.
* - In other cases, a string `'function'` is returned.
*
* When `value` is an Object:
*
* - When the object contains a property `format` being a function, this
* function is invoked as `value.format(options)` and the result is returned.
* - When the object has its own `toString` method, this method is invoked
* and the result is returned.
* - In other cases the function will loop over all object properties and
* return JSON object notation like '{"a": 2, "b": 3}'.
*
* Example usage:
* math.format(2/7) // '0.2857142857142857'
* math.format(math.pi, 3) // '3.14'
* math.format(new Complex(2, 3)) // '2 + 3i'
* math.format('hello') // '"hello"'
*
* @param {*} value Value to be stringified
* @param {Object | number | Function} [options] Formatting options. See
* lib/utils/number:format for a
* description of the available
* options.
* @return {string} str
*/
export function format (value, options) {
if (typeof value === 'number') {
return formatNumber(value, options)
}
if (isBigNumber(value)) {
return formatBigNumber(value, options)
}
// note: we use unsafe duck-typing here to check for Fractions, this is
// ok here since we're only invoking toString or concatenating its values
if (looksLikeFraction(value)) {
if (!options || options.fraction !== 'decimal') {
// output as ratio, like '1/3'
return (value.s * value.n) + '/' + value.d
} else {
// output as decimal, like '0.(3)'
return value.toString()
}
}
if (Array.isArray(value)) {
return formatArray(value, options)
}
if (isString(value)) {
return '"' + value + '"'
}
if (typeof value === 'function') {
return value.syntax ? String(value.syntax) : 'function'
}
if (value && typeof value === 'object') {
if (typeof value.format === 'function') {
return value.format(options)
} else if (value && value.toString(options) !== {}.toString()) {
// this object has a non-native toString method, use that one
return value.toString(options)
} else {
const entries = Object.keys(value).map(key => {
return '"' + key + '": ' + format(value[key], options)
})
return '{' + entries.join(', ') + '}'
}
}
return String(value)
}
/**
* Stringify a value into a string enclosed in double quotes.
* Unescaped double quotes and backslashes inside the value are escaped.
* @param {*} value
* @return {string}
*/
export function stringify (value) {
const text = String(value)
let escaped = ''
let i = 0
while (i < text.length) {
let c = text.charAt(i)
if (c === '\\') {
escaped += c
i++
c = text.charAt(i)
if (c === '' || '"\\/bfnrtu'.indexOf(c) === -1) {
escaped += '\\' // no valid escape character -> escape it
}
escaped += c
} else if (c === '"') {
escaped += '\\"'
} else {
escaped += c
}
i++
}
return '"' + escaped + '"'
}
/**
* Escape special HTML characters
* @param {*} value
* @return {string}
*/
export function escape (value) {
let text = String(value)
text = text.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
return text
}
/**
* Recursively format an n-dimensional matrix
* Example output: "[[1, 2], [3, 4]]"
* @param {Array} array
* @param {Object | number | Function} [options] Formatting options. See
* lib/utils/number:format for a
* description of the available
* options.
* @returns {string} str
*/
function formatArray (array, options) {
if (Array.isArray(array)) {
let str = '['
const len = array.length
for (let i = 0; i < len; i++) {
if (i !== 0) {
str += ', '
}
str += formatArray(array[i], options)
}
str += ']'
return str
} else {
return format(array, options)
}
}
/**
* Check whether a value looks like a Fraction (unsafe duck-type check)
* @param {*} value
* @return {boolean}
*/
function looksLikeFraction (value) {
return (value &&
typeof value === 'object' &&
typeof value.s === 'number' &&
typeof value.n === 'number' &&
typeof value.d === 'number') || false
}
/**
* Compare two strings
* @param {string} x
* @param {string} y
* @returns {number}
*/
export function compareText (x, y) {
// we don't want to convert numbers to string, only accept string input
if (!isString(x)) {
throw new TypeError('Unexpected type of argument in function compareText ' +
'(expected: string or Array or Matrix, actual: ' + typeOf(x) + ', index: 0)')
}
if (!isString(y)) {
throw new TypeError('Unexpected type of argument in function compareText ' +
'(expected: string or Array or Matrix, actual: ' + typeOf(y) + ', index: 1)')
}
return (x === y)
? 0
: (x > y ? 1 : -1)
}