-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.js
55 lines (49 loc) · 1.24 KB
/
utilities.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
/** @format */
const debug = require('debug')('utilities')
function padToTwoCharacters(x, padWithChar = '0') {
debug(`padToTwoCharacters(${x}, ${padWithChar}) called...`)
if (x.toString().length < 2) {
debug(`...returning ${padWithChar.concat(x)}`)
return padWithChar.concat(x)
} else {
return x
}
}
/*
* Calculate moving average
* Uses forEach loop
* Slightly more performant for smaller periods
*/
function calcMovingAverage(arr, per, emptyVal = 0) {
if (arr.length <= per) {
console.error(
`Array must be longer than the period ${per}. Supplied array is only ${arr.length} elements.`
)
return []
}
console.time('calcMovingAverage')
let ndx = -1
let resp = []
arr.forEach((n) => {
ndx++
if (ndx >= per - 1) {
resp.push(arr.slice(ndx - per + 1, ndx + 1).reduce((a, c) => a + c) / per)
} else {
resp.push(emptyVal)
}
})
console.timeEnd('calcMovingAverage')
return resp
}
function tagCache(c, ttl = 0) {
if (c.cache && c.cache.status) {
// Not stamped yet
c.cache.status = 'used'
}
return c
}
const CACHE_TTL = 600
exports.CACHE_TTL = CACHE_TTL
exports.tagCache = tagCache
exports.padToTwoCharacters = padToTwoCharacters
exports.calcMovingAverage = calcMovingAverage