When importing functions from separate files, they may not have access to the specific math.js instance they are being imported into. Factory functions solve this by allowing you to inject dependencies (like multiply or unaryMinus) at creation time.
This pattern ensures your functions work correctly across different math.js configurations (e.g., when switching between standard numbers and BigNumber or Decimal).
Syntax
factory(name: string, dependencies: string[], create: function, meta?: Object)
name: The name of the created function.dependencies: An array of names of the functions/values to inject.create: A function that receives an object containing the dependencies as its first argument.meta: An optional object for configuration:isClass: If true, the function is treated as a class (not exposed in the expression parser).lazy: If true (default), the function is only constructed when used. Set lazy: false to force immediate creation.isTransformFunction: If true, it is imported only in the internal mathWithTransform namespace for the parser.recreateOnConfigChange: If true, the factory is re-run when math.js configuration changes (useful for constants like pi).formerly: A string providing a deprecated synonym for the function name.
import { factory, create, all } from 'mathjs'
// Define the factory
const name = 'negativeSquare'
const dependencies = ['multiply', 'unaryMinus']
const createNegativeSquare = factory(name, dependencies, function ({ multiply, unaryMinus }) {
return function negativeSquare (x) {
return unaryMinus(multiply(x, x))
}
})
// Import the factory into a mathjs instance
const math = create(all)
math.import(createNegativeSquare)
console.log(math.negativeSquare(4)) // -16
console.log(math.evaluate('negativeSquare(5)')) // -25