FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
mathjs/examples/advanced/custom_datatype.js at develop · lineCode/mathjs · GitHub
lineCode
/
mathjs
Public
forked from
josdejong/mathjs
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
mathjs
/
examples
/
advanced
/
custom_datatype.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
56 lines (48 loc) · 1.75 KB
Breadcrumbs
mathjs
/
examples
/
advanced
/
custom_datatype.js
Copy path
File metadata and controls
56 lines (48 loc) · 1.75 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// This example demonstrates importing a custom data type,
// and extending an existing function (add) with support for this data type.
const
{
create
,
factory
,
all
}
=
require
(
'../..'
)
const
math
=
create
(
all
)
// factory function which defines a new data type CustomValue
const
createCustomValue
=
factory
(
'CustomValue'
,
[
'typed'
]
,
(
{
typed
}
)
=>
{
// create a new data type
function
CustomValue
(
value
)
{
this
.
value
=
value
}
CustomValue
.
prototype
.
isCustomValue
=
true
CustomValue
.
prototype
.
toString
=
function
(
)
{
return
'CustomValue:'
+
this
.
value
}
// define a new data type with typed-function
typed
.
addType
(
{
name
:
'CustomValue'
,
test
:
function
(
x
)
{
// test whether x is of type CustomValue
return
x
&&
x
.
isCustomValue
===
true
}
}
)
return
CustomValue
}
)
// function add which can add the CustomValue data type
// When imported in math.js, the existing function `add` with support for
// CustomValue, because both implementations are typed-functions and do not
// have conflicting signatures.
const
createAddCustomValue
=
factory
(
'add'
,
[
'typed'
,
'CustomValue'
]
,
(
{
typed
,
CustomValue
}
)
=>
{
return
typed
(
'add'
,
{
'CustomValue, CustomValue'
:
function
(
a
,
b
)
{
return
new
CustomValue
(
a
.
value
+
b
.
value
)
}
}
)
}
)
// import the new data type and function
math
.
import
(
[
createCustomValue
,
createAddCustomValue
]
)
// use the new type
const
ans1
=
math
.
add
(
new
math
.
CustomValue
(
2
)
,
new
math
.
CustomValue
(
3
)
)
console
.
log
(
ans1
.
toString
(
)
)
// outputs 'CustomValue:5'
// you can automatically use the new type in functions which use `add` under the hood:
const
ans2
=
math
.
sum
(
new
math
.
CustomValue
(
6
)
,
new
math
.
CustomValue
(
1
)
,
new
math
.
CustomValue
(
2
)
)
console
.
log
(
ans2
.
toString
(
)
)
// outputs 'CustomValue:9'
Back
|
FazBrowse Home
|
New Git URL