From d97f338fccd5fa6bdf591d34946a8794997fcb1b Mon Sep 17 00:00:00 2001 From: Jos de Jong Date: Thu, 25 Apr 2024 08:35:49 +0200 Subject: [PATCH] chore: replace util functions `values` and `contains` and usages of `indexOf` with using native JS functions `values` and `contains` (see #3194) --- bin/cli.js | 2 +- src/core/function/config.js | 12 +----------- src/core/function/import.js | 7 +++---- src/expression/parse.js | 4 ++-- src/function/algebra/derivative.js | 2 +- src/function/algebra/rationalize.js | 4 ++-- src/function/algebra/simplifyConstant.js | 2 +- src/function/statistics/mad.js | 2 +- src/function/statistics/std.js | 2 +- src/function/statistics/utils/improveErrorMessage.js | 4 ++-- src/utils/array.js | 10 ---------- src/utils/bignumber/formatter.js | 2 +- src/utils/factory.js | 3 +-- src/utils/object.js | 2 +- src/utils/snapshot.js | 8 ++++---- test/node-tests/browser.test.js | 4 ++-- test/node-tests/doc.test.js | 2 +- tools/docgenerator.js | 12 ++++++------ tools/entryGenerator.js | 8 ++++---- tools/matrixmarket.js | 8 ++++---- 20 files changed, 39 insertions(+), 61 deletions(-) diff --git a/bin/cli.js b/bin/cli.js index 664f6a640e..4943276d29 100755 --- a/bin/cli.js +++ b/bin/cli.js @@ -113,7 +113,7 @@ function completer (text) { const ignore = ['expr', 'type'] for (const func in math.expression.mathWithTransform) { if (hasOwnProperty(math.expression.mathWithTransform, func)) { - if (func.indexOf(keyword) === 0 && ignore.indexOf(func) === -1) { + if (func.indexOf(keyword) === 0 && !ignore.includes(func)) { matches.push(func) } } diff --git a/src/core/function/config.js b/src/core/function/config.js index b93f76fae1..b7701c898d 100644 --- a/src/core/function/config.js +++ b/src/core/function/config.js @@ -87,16 +87,6 @@ export function configFactory (config, emit) { return _config } -/** - * Test whether an Array contains a specific item. - * @param {Array.} array - * @param {string} item - * @return {boolean} - */ -function contains (array, item) { - return array.indexOf(item) !== -1 -} - /** * Validate an option * @param {Object} options Object with options @@ -104,7 +94,7 @@ function contains (array, item) { * @param {Array.} values Array with valid values for this option */ function validateOption (options, name, values) { - if (options[name] !== undefined && !contains(values, options[name])) { + if (options[name] !== undefined && !values.includes(options[name])) { // unknown value console.warn('Warning: Unknown value "' + options[name] + '" for configuration option "' + name + '". ' + 'Available options: ' + values.map(value => JSON.stringify(value)).join(', ') + '.') diff --git a/src/core/function/import.js b/src/core/function/import.js index ac7c5980cc..0b7d890a29 100644 --- a/src/core/function/import.js +++ b/src/core/function/import.js @@ -1,7 +1,6 @@ import { isBigNumber, isComplex, isFraction, isMatrix, isUnit } from '../../utils/is.js' import { isFactory, stripOptionalNotation } from '../../utils/factory.js' import { hasOwnProperty, lazy } from '../../utils/object.js' -import { contains } from '../../utils/array.js' import { ArgumentsError } from '../../error/ArgumentsError.js' export function importFactory (typed, load, math, importedFactories) { @@ -235,7 +234,7 @@ export function importFactory (typed, load, math, importedFactories) { * @private */ function _importFactory (factory, options, name = factory.fn) { - if (contains(name, '.')) { + if (name.includes('.')) { throw new Error('Factory name should not contain a nested path. ' + 'Name: ' + JSON.stringify(name)) } @@ -253,7 +252,7 @@ export function importFactory (typed, load, math, importedFactories) { factory.dependencies .map(stripOptionalNotation) .forEach(dependency => { - if (contains(dependency, '.')) { + if (dependency.includes('.')) { throw new Error('Factory dependency should not contain a nested path. ' + 'Name: ' + JSON.stringify(dependency)) } @@ -353,7 +352,7 @@ export function importFactory (typed, load, math, importedFactories) { } function factoryAllowedInExpressions (factory) { - return factory.fn.indexOf('.') === -1 && // FIXME: make checking on path redundant, check on meta data instead + return !factory.fn.includes('.') && // FIXME: make checking on path redundant, check on meta data instead !hasOwnProperty(unsafe, factory.fn) && (!factory.meta || !factory.meta.isClass) } diff --git a/src/expression/parse.js b/src/expression/parse.js index ef7a8e00b0..59db000a2c 100644 --- a/src/expression/parse.js +++ b/src/expression/parse.js @@ -1341,7 +1341,7 @@ export const createParse = /* #__PURE__ */ factory(name, dependencies, ({ if (hasOwnProperty(CONSTANTS, name)) { // true, false, null, ... node = new ConstantNode(CONSTANTS[name]) - } else if (NUMERIC_CONSTANTS.indexOf(name) !== -1) { // NaN, Infinity + } else if (NUMERIC_CONSTANTS.includes(name)) { // NaN, Infinity node = new ConstantNode(numeric(name, 'number')) } else { node = new SymbolNode(name) @@ -1373,7 +1373,7 @@ export const createParse = /* #__PURE__ */ factory(name, dependencies, ({ let params while ((state.token === '(' || state.token === '[' || state.token === '.') && - (!types || types.indexOf(state.token) !== -1)) { // eslint-disable-line no-unmodified-loop-condition + (!types || types.includes(state.token))) { // eslint-disable-line no-unmodified-loop-condition params = [] if (state.token === '(') { diff --git a/src/function/algebra/derivative.js b/src/function/algebra/derivative.js index 1b78447475..078ed03880 100644 --- a/src/function/algebra/derivative.js +++ b/src/function/algebra/derivative.js @@ -172,7 +172,7 @@ export const createDerivative = /* #__PURE__ */ factory(name, dependencies, ({ }, 'Object, FunctionAssignmentNode, string': function (constNodes, node, varName) { - if (node.params.indexOf(varName) === -1) { + if (!node.params.includes(varName)) { constNodes[node] = true return true } diff --git a/src/function/algebra/rationalize.js b/src/function/algebra/rationalize.js index be7415db37..4c901ee08f 100644 --- a/src/function/algebra/rationalize.js +++ b/src/function/algebra/rationalize.js @@ -252,7 +252,7 @@ export const createRationalize = /* #__PURE__ */ factory(name, dependencies, ({ recPoly(node.args[0]) } } else { - if (oper.indexOf(node.op) === -1) { + if (!oper.includes(node.op)) { throw new Error('Operator ' + node.op + ' invalid in polynomial expression') } for (let i = 0; i < node.args.length; i++) { @@ -536,7 +536,7 @@ export const createRationalize = /* #__PURE__ */ factory(name, dependencies, ({ throw new Error('There is an unsolved function call') } else if (tp === 'OperatorNode') { // ***** OperatorName ***** - if ('+-*^'.indexOf(node.op) === -1) throw new Error('Operator ' + node.op + ' invalid') + if (!'+-*^'.includes(node.op)) throw new Error('Operator ' + node.op + ' invalid') if (noPai !== null) { // -(unary),^ : children of *,+,- diff --git a/src/function/algebra/simplifyConstant.js b/src/function/algebra/simplifyConstant.js index d5f3888b57..f408bcd989 100644 --- a/src/function/algebra/simplifyConstant.js +++ b/src/function/algebra/simplifyConstant.js @@ -355,7 +355,7 @@ export const createSimplifyConstant = /* #__PURE__ */ factory(name, dependencies { // Process operators as OperatorNode const operatorFunctions = ['add', 'multiply'] - if (operatorFunctions.indexOf(node.name) === -1) { + if (!operatorFunctions.includes(node.name)) { const args = node.args.map(arg => foldFraction(arg, options)) // If all args are numbers diff --git a/src/function/statistics/mad.js b/src/function/statistics/mad.js index baa7fa75b1..3ad14ce9bc 100644 --- a/src/function/statistics/mad.js +++ b/src/function/statistics/mad.js @@ -53,7 +53,7 @@ export const createMad = /* #__PURE__ */ factory(name, dependencies, ({ typed, a return abs(subtract(value, med)) })) } catch (err) { - if (err instanceof TypeError && err.message.indexOf('median') !== -1) { + if (err instanceof TypeError && err.message.includes('median')) { throw new TypeError(err.message.replace('median', 'mad')) } else { throw improveErrorMessage(err, 'mad') diff --git a/src/function/statistics/std.js b/src/function/statistics/std.js index 7f6d33ba12..baab24fe3d 100644 --- a/src/function/statistics/std.js +++ b/src/function/statistics/std.js @@ -88,7 +88,7 @@ export const createStd = /* #__PURE__ */ factory(name, dependencies, ({ typed, m return sqrt(v) } } catch (err) { - if (err instanceof TypeError && err.message.indexOf(' variance') !== -1) { + if (err instanceof TypeError && err.message.includes(' variance')) { throw new TypeError(err.message.replace(' variance', ' std')) } else { throw err diff --git a/src/function/statistics/utils/improveErrorMessage.js b/src/function/statistics/utils/improveErrorMessage.js index e31a71bfba..a4375f6caf 100644 --- a/src/function/statistics/utils/improveErrorMessage.js +++ b/src/function/statistics/utils/improveErrorMessage.js @@ -14,7 +14,7 @@ export function improveErrorMessage (err, fnName, value) { // TODO: add information with the index (also needs transform in expression parser) let details - if (String(err).indexOf('Unexpected type') !== -1) { + if (String(err).includes('Unexpected type')) { details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : ' (type: ' + err.data.actual + ')' @@ -22,7 +22,7 @@ export function improveErrorMessage (err, fnName, value) { return new TypeError('Cannot calculate ' + fnName + ', unexpected type of argument' + details) } - if (String(err).indexOf('complex numbers') !== -1) { + if (String(err).includes('complex numbers')) { details = arguments.length > 2 ? ' (type: ' + typeOf(value) + ', value: ' + JSON.stringify(value) + ')' : '' diff --git a/src/utils/array.js b/src/utils/array.js index c510245a7b..f1006dfc67 100644 --- a/src/utils/array.js +++ b/src/utils/array.js @@ -650,16 +650,6 @@ export function initial (array) { return array.slice(0, array.length - 1) } -/** - * Test whether an array or string contains an item - * @param {Array | string} array - * @param {*} item - * @return {boolean} - */ -export function contains (array, item) { - return array.indexOf(item) !== -1 -} - /** * Recursively concatenate two matrices. * The contents of the matrices is not cloned. diff --git a/src/utils/bignumber/formatter.js b/src/utils/bignumber/formatter.js index f51b5ec5c2..b33bc495eb 100644 --- a/src/utils/bignumber/formatter.js +++ b/src/utils/bignumber/formatter.js @@ -201,7 +201,7 @@ export function toEngineering (value, precision) { const valueWithoutExp = value.mul(Math.pow(10, -newExp)) let valueStr = valueWithoutExp.toPrecision(precision) - if (valueStr.indexOf('e') !== -1) { + if (valueStr.includes('e')) { const BigNumber = value.constructor valueStr = new BigNumber(valueStr).toFixed() } diff --git a/src/utils/factory.js b/src/utils/factory.js index 32afaa763d..e12eeb1ea0 100644 --- a/src/utils/factory.js +++ b/src/utils/factory.js @@ -1,4 +1,3 @@ -import { contains } from './array.js' import { pickShallow } from './object.js' /** @@ -63,7 +62,7 @@ export function sortFactories (factories) { function containsDependency (factory, dependency) { // TODO: detect circular references if (isFactory(factory)) { - if (contains(factory.dependencies, dependency.fn || dependency.name)) { + if (factory.dependencies.includes(dependency.fn || dependency.name)) { return true } diff --git a/src/utils/object.js b/src/utils/object.js index 7fbbdbc4a5..5fd54dd1d0 100644 --- a/src/utils/object.js +++ b/src/utils/object.js @@ -392,5 +392,5 @@ export function pickShallow (object, properties) { // helper function to test whether a string contains a path like 'user.name' function isPath (str) { - return str.indexOf('.') !== -1 + return str.includes('.') } diff --git a/src/utils/snapshot.js b/src/utils/snapshot.js index d610013fc6..7cbdbf7009 100644 --- a/src/utils/snapshot.js +++ b/src/utils/snapshot.js @@ -16,7 +16,7 @@ export function validateBundle (expectedBundleStructure, bundle) { const originalWarn = console.warn console.warn = function (...args) { - if (args.join(' ').indexOf('is moved to') !== -1 && args.join(' ').indexOf('Please use the new location instead') !== -1) { + if (args.join(' ').includes('is moved to') && args.join(' ').includes('Please use the new location instead')) { // Ignore warnings like: // Warning: math.type.isNumber is moved to math.isNumber in v6.0.0. Please use the new location instead. return @@ -52,11 +52,11 @@ export function validateBundle (expectedBundleStructure, bundle) { const expectedType = get(expectedBundleStructure, path) || 'undefined' // FIXME: ugly to have these special cases - if (path.join('.').indexOf('docs.') !== -1) { + if (path.join('.').includes('docs.')) { // ignore the contents of docs return } - if (path.join('.').indexOf('all.') !== -1) { + if (path.join('.').includes('all.')) { // ignore the contents of all dependencies return } @@ -237,7 +237,7 @@ export function createSnapshotFromFactories (factories) { function traverse (obj, callback = (value, path) => {}, path = []) { // FIXME: ugly to have these special cases - if (path.length > 0 && path[0].indexOf('Dependencies') !== -1) { + if (path.length > 0 && path[0].includes('Dependencies')) { // special case for objects holding a collection of dependencies callback(obj, path) } else if (validateTypeOf(obj) === 'Array') { diff --git a/test/node-tests/browser.test.js b/test/node-tests/browser.test.js index b5e6198490..a9ef97776c 100644 --- a/test/node-tests/browser.test.js +++ b/test/node-tests/browser.test.js @@ -22,7 +22,7 @@ describe('lib/browser', function () { // don't output all warnings "math.foo.bar is move to math.bar, ..." const originalWarn = console.warn console.warn = (...args) => { - if (args.join(' ').indexOf('is moved to') === -1) { + if (!args.join(' ').includes('is moved to')) { originalWarn.apply(console, args) } } @@ -85,7 +85,7 @@ describe('lib/browser', function () { const obj = math[prop] if (math.typeOf(obj) !== 'Object') { try { - if (ignore.indexOf(prop) === -1) { + if (!ignore.includes(prop)) { math.help(prop).toString() } } catch (err) { diff --git a/test/node-tests/doc.test.js b/test/node-tests/doc.test.js index e64a8b9872..f640732916 100644 --- a/test/node-tests/doc.test.js +++ b/test/node-tests/doc.test.js @@ -5,7 +5,7 @@ const approx = require('../../tools/approx.js') const docgenerator = require('../../tools/docgenerator.js') const math = require('../..') -const debug = process.argv.indexOf('--debug-docs') !== -1 +const debug = process.argv.includes('--debug-docs') function extractExpectation (comment, optional = false) { if (comment === '') return undefined diff --git a/tools/docgenerator.js b/tools/docgenerator.js index bcecb5246d..4f0ff0b93f 100644 --- a/tools/docgenerator.js +++ b/tools/docgenerator.js @@ -378,7 +378,7 @@ function validateDoc (doc) { const issues = [] function ignore (field) { - return IGNORE_WARNINGS[field].indexOf(doc.name) !== -1 + return IGNORE_WARNINGS[field].includes(doc.name) } if (!doc.name) { @@ -558,10 +558,10 @@ function collectDocs (functionNames, inputPath) { let category // Note: determining whether a file is a function and what it's category - // is is a bit tricky and quite specific to the structure of the code, + // is a bit tricky and quite specific to the structure of the code, // we reckon with some edge cases here. - if (path.indexOf('docs') === -1 && functionIndex !== -1) { - if (path.indexOf('expression') !== -1) { + if (!path.includes('docs') && functionIndex !== -1) { + if (path.includes('expression')) { category = 'expression' } else if (/\/lib\/cjs\/type\/[a-zA-Z0-9_]*\/function/.test(fullPath)) { // for type/bignumber/function/bignumber.js, type/fraction/function/fraction.js, etc @@ -579,7 +579,7 @@ function collectDocs (functionNames, inputPath) { category = 'construction' } - if (functionNames.indexOf(name) === -1 || IGNORE_FUNCTIONS[name]) { + if (!functionNames.includes(name) || IGNORE_FUNCTIONS[name]) { category = null } @@ -601,7 +601,7 @@ function collectDocs (functionNames, inputPath) { const fn = functions[name] const code = String(fs.readFileSync(fn.fullPath)) - const isFunction = (functionNames.indexOf(name) !== -1) && !IGNORE_FUNCTIONS[name] + const isFunction = (functionNames.includes(name)) && !IGNORE_FUNCTIONS[name] const doc = isFunction ? generateDoc(name, code) : null if (isFunction && doc) { diff --git a/tools/entryGenerator.js b/tools/entryGenerator.js index bc63e4df4c..56f478f3bb 100644 --- a/tools/entryGenerator.js +++ b/tools/entryGenerator.js @@ -221,7 +221,7 @@ function generateDependenciesFiles ({ suffix, factories, entryFolder }) { .filter(dependency => !IGNORED_DEPENDENCIES[dependency]) .filter(dependency => { if (!exists[dependency]) { - if (factory.dependencies.indexOf(dependency) !== -1) { + if (factory.dependencies.includes(dependency)) { throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}" (suffix: ${suffix})`) } @@ -348,7 +348,7 @@ function generateFunctionsFiles ({ suffix, factories, entryFolder }) { .filter(dependency => { // TODO: this code is duplicated. extract it in a separate function if (!pureExists[dependency]) { - if (factory.dependencies.indexOf(dependency) !== -1) { + if (factory.dependencies.includes(dependency)) { throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}" (suffix: ${suffix})`) } @@ -381,7 +381,7 @@ function generateFunctionsFiles ({ suffix, factories, entryFolder }) { // TODO: this code is duplicated. extract it in a separate function if (!impureExists[dependency]) { - // if (factory.dependencies.indexOf(dependency) !== -1) { + // if (factory.dependencies.includes(dependency)) { // throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`) // } @@ -414,7 +414,7 @@ function generateFunctionsFiles ({ suffix, factories, entryFolder }) { // TODO: this code is duplicated. extract it in a separate function if (!impureExists[dependency]) { - // if (factory.dependencies.indexOf(dependency) !== -1) { + // if (factory.dependencies.includes(dependency)) { // throw new Error(`Required dependency "${dependency}" missing for factory "${factory.fn}"`) // } diff --git a/tools/matrixmarket.js b/tools/matrixmarket.js index 3e32b1f870..406ad8022d 100644 --- a/tools/matrixmarket.js +++ b/tools/matrixmarket.js @@ -37,27 +37,27 @@ const _importFromStream = function (stream) { const datatype = matches[3] const qualifier = matches[4] // check typecode - if (typecodes.indexOf(typecode) === -1) { + if (!typecodes.includes(typecode)) { // typecode not supported reject(new Error('Matrix Market type code is not supported: ' + typecode)) // close stream stream.close() } // check format - if (formats.indexOf(format) === -1) { + if (!formats.includes(format)) { // typecode not supported reject(new Error('Matrix Market format is not supported: ' + format)) // close stream stream.close() } // check datatype - if (datatypes.indexOf(datatype) === -1) { + if (!datatypes.includes(datatype)) { // typecode not supported reject(new Error('Matrix Market datatype is not supported: ' + datatype)) // close stream stream.close() } - if (qualifiers.indexOf(qualifier) === -1) { + if (!qualifiers.includes(qualifier)) { // typecode not supported reject(new Error('Matrix Market qualifier is not supported: ' + qualifier)) // close stream