@cloudpss/template
Version:
Lightweight string and object templating utilities with interpolation and formula support.
44 lines • 1.25 kB
JavaScript
import { compileSync } from '@mirascript/mirascript';
import { LRUCache } from 'lru-cache';
const CACHE_SIZE = 100;
const formula = new LRUCache({
max: CACHE_SIZE,
memoMethod: (template) => {
const formula = template.slice(1);
const value = compileSync(formula, { input_mode: 'Script' });
return {
type: 'formula',
value: value,
};
},
});
const interpolation = new LRUCache({
max: CACHE_SIZE,
memoMethod: (template) => {
const expr = template.slice(1);
const value = compileSync(expr, { input_mode: 'Template' });
return {
type: 'interpolation',
value: value,
};
},
});
/**
* 解析字符串模板
* - 长度大于 1
* - 如果模板以 `=` 开头,则表示是一个公式
* - 如果模板以 `$` 开头,则表示是一个插值模板
* - 否则表示是一个普通字符串
*/
export function parseTemplate(template) {
if (template.length <= 1)
return template;
if (template.startsWith('=')) {
return formula.memo(template);
}
if (template.startsWith('$')) {
return interpolation.memo(template);
}
return template;
}
//# sourceMappingURL=parser.js.map