preserves/implementations/javascript/src/text.ts

23 lines
584 B
TypeScript
Raw Normal View History

import { Value } from './values';
2021-01-09 15:21:25 +00:00
export function stringify(x: any): string {
2021-01-11 15:54:52 +00:00
if (typeof x?.asPreservesText === 'function') {
return x.asPreservesText();
} else {
2021-01-09 15:21:25 +00:00
try {
return JSON.stringify(x);
} catch (_e) {
return ('' + x).asPreservesText();
}
}
}
2021-01-29 11:03:28 +00:00
export function preserves(pieces: TemplateStringsArray, ...values: Value<any>[]): string {
const result = [pieces[0]];
values.forEach((v, i) => {
result.push(stringify(v));
result.push(pieces[i + 1]);
});
return result.join('');
}