-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmisc.js
57 lines (53 loc) · 1.59 KB
/
misc.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
import { ATTRIBUTE, VALUE } from './expression-types.js'
import { dashToCamelCase } from './strings.js'
/**
* Throw an error with a descriptive message
* @param { string } message - error message
* @param { string } cause - optional error cause object
* @returns { undefined } hoppla... at this point the program should stop working
*/
export function panic(message, cause) {
throw new Error(message, { cause })
}
/**
* Returns the memoized (cached) function.
* // borrowed from https://www.30secondsofcode.org/js/s/memoize
* @param {Function} fn - function to memoize
* @returns {Function} memoize function
*/
export function memoize(fn) {
const cache = new Map()
const cached = (val) => {
return cache.has(val)
? cache.get(val)
: cache.set(val, fn.call(this, val)) && cache.get(val)
}
cached.cache = cache
return cached
}
/**
* Evaluate a list of attribute expressions
* @param {Array} attributes - attribute expressions generated by the riot compiler
* @returns {Object} key value pairs with the result of the computation
*/
export function evaluateAttributeExpressions(attributes) {
return attributes.reduce((acc, attribute) => {
const { value, type } = attribute
switch (true) {
// spread attribute
case !attribute.name && type === ATTRIBUTE:
return {
...acc,
...value,
}
// value attribute
case type === VALUE:
acc.value = attribute.value
break
// normal attributes
default:
acc[dashToCamelCase(attribute.name)] = attribute.value
}
return acc
}, {})
}