-
Notifications
You must be signed in to change notification settings - Fork 9
/
math.js
61 lines (56 loc) · 1.89 KB
/
math.js
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
57
58
59
60
61
import ieee754 from 'ieee754'
// simple utility to scale a value to a range
export function getScaledValue (value, sourceRangeMin, sourceRangeMax, targetRangeMin = 0, targetRangeMax = 100) {
const targetRange = targetRangeMax - targetRangeMin
const sourceRange = sourceRangeMax - sourceRangeMin
return (value - sourceRangeMin) * targetRange / sourceRange + targetRangeMin
}
// These do byte-operations without Buffer (for browser)
// lots of ideas from https://github.com/feross/buffer
export function toInt16 (buffer) {
if ((buffer.length % 2) !== 0) {
throw new Error('Byte-length not divisible by 2.')
}
const out = (new Int16Array(buffer.length / 2)).map((v, i) => {
const n = i * 2
const val = buffer[n + 1] | (buffer[n] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
})
return out.length === 1 ? out[0] : out
}
export function toUInt16 (buffer) {
if ((buffer.length % 2) !== 0) {
throw new Error('Byte-length not divisible by 2.')
}
const out = (new Uint16Array(buffer.length / 2)).map((v, i) => {
const n = i * 2
return (buffer[n] << 8) | buffer[n + 1]
})
return out.length === 1 ? out[0] : out
}
export function toUInt24 (buffer) {
if ((buffer.length % 3) !== 0) {
throw new Error('Byte-length not divisible by 3.')
}
const out = (new Uint32Array(buffer.length / 3)).map((v, i) => {
const n = i * 3
let byteLength = 3
let val = buffer[n + --byteLength]
let mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += buffer[n + --byteLength] * mul
}
return val
})
return out.length === 1 ? out[0] : out
}
export function toFloat32 (buffer) {
if ((buffer.length % 4) !== 0) {
throw new Error('Byte-length not divisible by 4.')
}
const out = (new Float32Array(buffer.length / 4)).map((v, i) => {
const n = i * 4
return ieee754.read(buffer, n, false, 23, 4)
})
return out.length === 1 ? out[0] : out
}