Skip to content

Commit

Permalink
chore: replace util functions values and contains and usages of `…
Browse files Browse the repository at this point in the history
…indexOf` with using native JS functions `values` and `contains` (see #3194)
  • Loading branch information
josdejong committed Apr 25, 2024
1 parent e37bacd commit d97f338
Show file tree
Hide file tree
Showing 20 changed files with 39 additions and 61 deletions.
2 changes: 1 addition & 1 deletion bin/cli.js
Expand Up @@ -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)
}
}
Expand Down
12 changes: 1 addition & 11 deletions src/core/function/config.js
Expand Up @@ -87,24 +87,14 @@ export function configFactory (config, emit) {
return _config
}

/**
* Test whether an Array contains a specific item.
* @param {Array.<string>} array
* @param {string} item
* @return {boolean}
*/
function contains (array, item) {
return array.indexOf(item) !== -1
}

/**
* Validate an option
* @param {Object} options Object with options
* @param {string} name Name of the option to validate
* @param {Array.<string>} 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(', ') + '.')
Expand Down
7 changes: 3 additions & 4 deletions 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) {
Expand Down Expand Up @@ -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))
}
Expand All @@ -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))
}
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions src/expression/parse.js
Expand Up @@ -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)
Expand Down Expand Up @@ -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 === '(') {
Expand Down
2 changes: 1 addition & 1 deletion src/function/algebra/derivative.js
Expand Up @@ -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
}
Expand Down
4 changes: 2 additions & 2 deletions src/function/algebra/rationalize.js
Expand Up @@ -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++) {
Expand Down Expand Up @@ -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 *,+,-
Expand Down
2 changes: 1 addition & 1 deletion src/function/algebra/simplifyConstant.js
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/function/statistics/mad.js
Expand Up @@ -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')
Expand Down
2 changes: 1 addition & 1 deletion src/function/statistics/std.js
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/function/statistics/utils/improveErrorMessage.js
Expand Up @@ -14,15 +14,15 @@ 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 + ')'

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) + ')'
: ''
Expand Down
10 changes: 0 additions & 10 deletions src/utils/array.js
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion src/utils/bignumber/formatter.js
Expand Up @@ -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()
}
Expand Down
3 changes: 1 addition & 2 deletions src/utils/factory.js
@@ -1,4 +1,3 @@
import { contains } from './array.js'
import { pickShallow } from './object.js'

/**
Expand Down Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion src/utils/object.js
Expand Up @@ -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('.')
}
8 changes: 4 additions & 4 deletions src/utils/snapshot.js
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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') {
Expand Down
4 changes: 2 additions & 2 deletions test/node-tests/browser.test.js
Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion test/node-tests/doc.test.js
Expand Up @@ -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
Expand Down
12 changes: 6 additions & 6 deletions tools/docgenerator.js
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand All @@ -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
}

Expand All @@ -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) {
Expand Down
8 changes: 4 additions & 4 deletions tools/entryGenerator.js
Expand Up @@ -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})`)
}

Expand Down Expand Up @@ -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})`)
}

Expand Down Expand Up @@ -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}"`)
// }

Expand Down Expand Up @@ -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}"`)
// }

Expand Down
8 changes: 4 additions & 4 deletions tools/matrixmarket.js
Expand Up @@ -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
Expand Down

0 comments on commit d97f338

Please sign in to comment.