UNPKG

riot

Version:

Simple and elegant component-based UI library

64 lines (58 loc) 1.81 kB
/* Riot WIP, @license MIT */ import { VALUE, ATTRIBUTE, REF } 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 */ 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 */ 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 */ function evaluateAttributeExpressions(attributes) { return attributes.reduce((acc, attribute) => { const { value, type } = attribute; switch (true) { // ref attributes shouldn't be evaluated in the props case attribute.type === REF: break // 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 }, {}) } export { evaluateAttributeExpressions, memoize, panic };