Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

number-looking like string should be escaped #282

Merged
merged 3 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/library/cbor/recordid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ export class StringRecordId {
}

function escape_ident(str: string) {
// String which looks like a number should always be escaped, to prevent it from being parsed as a number
if (isOnlyNumbers(str)) {
return `⟨${str}⟩`;
}

let code, i, len;

for (i = 0, len = str.length; i < len; i++) {
Expand All @@ -65,3 +70,8 @@ function escape_ident(str: string) {

return str;
}

function isOnlyNumbers(str: string) {
const parsed = parseInt(str);
return !isNaN(parsed) && parsed.toString() === str;
}
3 changes: 3 additions & 0 deletions tests/unit/__snapshots__/jsonify.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ snapshot[`jsonify matches snapshot 1`] = `
],
type: "GeometryCollection",
},
id_almost_a_number: "⟨some:thing⟩:1e23",
id_is_a_number: "⟨some:thing⟩:123",
id_looks_like_number: "⟨some:thing⟩:⟨123⟩",
null: null,
num: 123,
rid: "⟨some:thing⟩:under_score",
Expand Down
3 changes: 3 additions & 0 deletions tests/unit/jsonify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Deno.test("jsonify matches snapshot", async function (t) {
const json = jsonify(
{
rid: new RecordId("some:thing", "under_score"),
id_looks_like_number: new RecordId("some:thing", "123"),
id_almost_a_number: new RecordId("some:thing", "1e23"),
id_is_a_number: new RecordId("some:thing", 123),
str_rid: new StringRecordId("⟨some:thing⟩:under_score"),
dec: new Decimal("3.333333"),
dur: new Duration("1d2h"),
Expand Down
Loading