feat: Add vector constructor/converter
This commit is contained in:
parent
cc4d77f128
commit
7d150e2860
4 changed files with 35 additions and 0 deletions
|
@ -22,6 +22,10 @@ export const Vector = new Type(isVector, {
|
|||
specializesTo: VT => this.specializesTo(VT)
|
||||
&& CompType.specializesTo(VT.Component),
|
||||
refine: (v, typer) => {
|
||||
if (!v.length) {
|
||||
throw new RangeError(
|
||||
`no way to refine ${typeName} on an empty vector`)
|
||||
}
|
||||
const eltTypes = v.map(elt => CompType.refine(elt, typer))
|
||||
const newCompType = eltTypes[0]
|
||||
if (eltTypes.some(T => T !== newCompType)) {
|
||||
|
@ -35,6 +39,7 @@ export const Vector = new Type(isVector, {
|
|||
},
|
||||
specializesTo: VT => VT.vector,
|
||||
refine(v, typer) {
|
||||
if (!v.length) return this.specialize(NotAType) // what else could we do?
|
||||
const eltTypes = v.map(elt => typer(elt))
|
||||
let compType = eltTypes[0]
|
||||
if (eltTypes.some(T => T !== compType)) compType = NotAType
|
||||
|
|
16
src/vector/__test__/type.js
Normal file
16
src/vector/__test__/type.js
Normal file
|
@ -0,0 +1,16 @@
|
|||
import assert from 'assert'
|
||||
import {NotAType} from '#core/Type.js'
|
||||
import math from '#nanomath'
|
||||
|
||||
describe('Vector type functions', () => {
|
||||
it('can construct a vector', () => {
|
||||
const vec = math.vector
|
||||
const {BooleanT, NumberT, Vector} = math.types
|
||||
assert.deepStrictEqual(vec(3, 4, 5), [3, 4, 5])
|
||||
assert.strictEqual(
|
||||
vec.resolve([NumberT, NumberT, NumberT]).returns, Vector(NumberT))
|
||||
assert.deepStrictEqual(vec(3, true), [3, true])
|
||||
assert.strictEqual(
|
||||
vec.resolve([NumberT, BooleanT]).returns, Vector(NotAType))
|
||||
})
|
||||
})
|
|
@ -1 +1,3 @@
|
|||
export * as typeDefinition from './Vector.js'
|
||||
export * as type from './type.js'
|
||||
|
||||
|
|
12
src/vector/type.js
Normal file
12
src/vector/type.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
import {Vector} from './Vector.js'
|
||||
import {NotAType, Returns} from '#core/Type.js'
|
||||
import {Any, Multiple, match} from '#core/TypePatterns.js'
|
||||
|
||||
export const vector = match(Multiple(Any), (math, TV) => {
|
||||
if (!TV.length) return Returns(Vector(NotAType), () => [])
|
||||
let CompType = TV[0]
|
||||
if (TV.some(T => T !== CompType)) CompType = NotAType
|
||||
return Returns(Vector(CompType), v => v)
|
||||
})
|
||||
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue