1 | const coerced = require('./coerced')
|
2 | const operators = require('./operators.json')
|
3 | const staticProps = require('static-props')
|
4 | const toData = require('./toData')
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | function createScalar (ring) {
|
13 | const attributes = {
|
14 | zero: ring.zero,
|
15 | one: ring.one,
|
16 | order: 0
|
17 | }
|
18 |
|
19 | |
20 |
|
21 |
|
22 |
|
23 | class Scalar {
|
24 | constructor (data) {
|
25 |
|
26 | if (ring.notContains(data)) {
|
27 | throw new TypeError('Invalid data = ' + data)
|
28 | }
|
29 |
|
30 | const enumerable = true
|
31 | staticProps(this)({ data }, enumerable)
|
32 |
|
33 | staticProps(this)(attributes)
|
34 | }
|
35 | }
|
36 |
|
37 | staticProps(Scalar)(attributes)
|
38 |
|
39 | const staticNary = (operator) => {
|
40 | Scalar[operator] = function () {
|
41 | var operands = [].slice.call(arguments).map(toData)
|
42 | return coerced(ring[operator]).apply(null, operands)
|
43 | }
|
44 | }
|
45 |
|
46 | var unaryOperators = operators.inversion
|
47 |
|
48 | unaryOperators.push('conjugation')
|
49 |
|
50 | unaryOperators.forEach((operator) => {
|
51 | Scalar[operator] = function (operand) {
|
52 | return ring[operator](toData(operand))
|
53 | }
|
54 |
|
55 | Scalar.prototype[operator] = function () {
|
56 | var data = Scalar[operator](this.data)
|
57 |
|
58 | return new Scalar(data)
|
59 | }
|
60 | })
|
61 |
|
62 | operators.group.concat(operators.ring).forEach((operator) => {
|
63 | staticNary(operator)
|
64 |
|
65 | Scalar.prototype[operator] = function () {
|
66 | const args = [].slice.call(arguments)
|
67 | const operands = [this.data].concat(args)
|
68 |
|
69 | const data = Scalar[operator].apply(null, operands)
|
70 |
|
71 | return new Scalar(data)
|
72 | }
|
73 | })
|
74 |
|
75 | operators.set.forEach((operator) => {
|
76 | staticNary(operator)
|
77 | })
|
78 |
|
79 | operators.comparison.forEach((operator) => {
|
80 | staticNary(operator)
|
81 |
|
82 | Scalar.prototype[operator] = function () {
|
83 | const args = [].slice.call(arguments)
|
84 | const operands = [this.data].concat(args)
|
85 |
|
86 | const bool = Scalar[operator].apply(null, operands)
|
87 |
|
88 | return bool
|
89 | }
|
90 | })
|
91 |
|
92 | Object.keys(operators.aliasesOf).forEach((operator) => {
|
93 | operators.aliasesOf[operator].forEach((alias) => {
|
94 | Scalar[alias] = Scalar[operator]
|
95 | Scalar.prototype[alias] = Scalar.prototype[operator]
|
96 | })
|
97 | })
|
98 |
|
99 | return Scalar
|
100 | }
|
101 |
|
102 | module.exports = createScalar
|