UNPKG

1.57 kBJavaScriptView Raw
1// This example demonstrates importing a custom data type,
2// and extending an existing function (add) with support for this data type.
3
4const { create, factory, all } = require('../..')
5const math = create(all)
6
7// factory function which defines a new data type CustomValue
8const createCustomValue = factory('CustomValue', ['typed'], ({ typed }) => {
9 // create a new data type
10 function CustomValue (value) {
11 this.value = value
12 }
13 CustomValue.prototype.isCustomValue = true
14 CustomValue.prototype.toString = function () {
15 return 'CustomValue:' + this.value
16 }
17
18 // define a new data type with typed-function
19 typed.addType({
20 name: 'CustomValue',
21 test: function (x) {
22 // test whether x is of type CustomValue
23 return x && x.isCustomValue === true
24 }
25 })
26
27 return CustomValue
28})
29
30// function add which can add the CustomValue data type
31// When imported in math.js, the existing function `add` with support for
32// CustomValue, because both implementations are typed-functions and do not
33// have conflicting signatures.
34const createAddCustomValue = factory('add', ['typed', 'CustomValue'], ({ typed, CustomValue }) => {
35 return typed('add', {
36 'CustomValue, CustomValue': function (a, b) {
37 return new CustomValue(a.value + b.value)
38 }
39 })
40})
41
42// import the new data type and function
43math.import([
44 createCustomValue,
45 createAddCustomValue
46])
47
48// use the new type
49const ans = math.add(new math.CustomValue(2), new math.CustomValue(3))
50// ans = CustomValue(5)
51
52console.log(ans.toString())
53// outputs 'CustomValue:5'