Add new datatypes

File: index.js (click for a live demo)

const math = require('../../../index')

// import the new type MyType and the function `add` in math.js
math.import(require('./MyType'))
math.import(require('./myAdd'))

// create a shortcut to the new type.
const MyType = math.type.MyType

// use the new type
const ans = math.add(new MyType(2), new MyType(3)) // returns MyType(5)
console.log(ans.toString()) // outputs 'MyType:5'

File: MyType.js (click for a live demo)

// Note: This file is used by the file ./index.js

// factory function which defines a new data type MyType
function factory (type, config, load, typed) {
  // create a new data type
  function MyType (value) {
    this.value = value
  }
  MyType.prototype.isMyType = true
  MyType.prototype.toString = function () {
    return 'MyType:' + this.value
  }

  // define a new data type
  typed.addType({
    name: 'MyType',
    test: function (x) {
      // test whether x is of type MyType
      return x && x.isMyType
    }
  })

  // return the construction function, this will
  // be added to math.type.MyType when imported
  return MyType
}

exports.name = 'MyType'
exports.path = 'type' // will be imported into math.type.MyType
exports.factory = factory
exports.lazy = false // disable lazy loading as this factory has side
// effects: it adds a type and a conversion.

File: myAdd.js (click for a live demo)

// Note: This file is used by the file ./index.js

function factory (type, config, load, typed) {
  // create a new typed function using MyType
  // when imported in math.js, this will extend the
  // existing function `add` with support for MyType
  return typed('add', {
    'MyType, MyType': function (a, b) {
      return new type.MyType(a.value + b.value)
    }
  })
}

exports.name = 'add'
exports.factory = factory

Fork me on GitHub