diff --git a/.changeset/good-lamps-serve.md b/.changeset/good-lamps-serve.md new file mode 100644 index 00000000..66736244 --- /dev/null +++ b/.changeset/good-lamps-serve.md @@ -0,0 +1,5 @@ +--- +"@ryanatkn/belt": patch +--- + +add `embed_json` helper for embedding parsed json strings in js diff --git a/src/lib/json.test.ts b/src/lib/json.test.ts index f9379071..9ac5abf1 100644 --- a/src/lib/json.test.ts +++ b/src/lib/json.test.ts @@ -1,10 +1,10 @@ import {test} from 'uvu'; import * as assert from 'uvu/assert'; -import {to_json_type} from '$lib/json.js'; +import {to_json_type, embed_json} from '$lib/json.js'; import {noop} from '$lib/function.js'; -test('basic behavior', () => { +test('to_json_type', () => { assert.is(to_json_type(''), 'string'); assert.is(to_json_type('1'), 'string'); assert.is(to_json_type(1), 'number'); @@ -20,4 +20,10 @@ test('basic behavior', () => { assert.is(to_json_type(Symbol() as any), undefined); }); +test('embed_json', () => { + assert.is(embed_json('hello"world'), `JSON.parse('"hello\\"world"')`); + assert.is(embed_json("hello'world"), `JSON.parse('"hello\\'world"')`); + assert.is(embed_json("'hello'w''or'''ld'"), `JSON.parse('"\\'hello\\'w\\'\\'or\\'\\'\\'ld\\'"')`); +}); + test.run(); diff --git a/src/lib/json.ts b/src/lib/json.ts index a821b103..8de2ce75 100644 --- a/src/lib/json.ts +++ b/src/lib/json.ts @@ -35,3 +35,10 @@ export const canonicalize = (value: T): T => { .map(([k, v]) => [k, canonicalize(v)]), ) as any; }; + +/** + * Embeds `data` as a JSON string, escaping single quotes. + * Useful for optimizing JSON in JS because it parses faster. + */ +export const embed_json = (data: T, stringify: (data: T) => string = JSON.stringify): string => + `JSON.parse('${stringify(data).replaceAll("'", "\\'")}')`; diff --git a/src/routes/package.ts b/src/routes/package.ts index e3149300..109dc665 100644 --- a/src/routes/package.ts +++ b/src/routes/package.ts @@ -207,6 +207,7 @@ export const src_json = { {name: 'Json_Type', kind: 'type'}, {name: 'to_json_type', kind: 'function'}, {name: 'canonicalize', kind: 'function'}, + {name: 'embed_json', kind: 'function'}, ], }, './log.js': {