Skip to content
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
14 changes: 14 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"overrides": [
{
"files": ["**/CHANGELOG.md", "**/vite.config.js.timestamp-*", "**/test-results/**"],
"options": {
"rangeEnd": 0
}
}
]
}
14 changes: 7 additions & 7 deletions benchmarking/benchmarks/typed-array.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default [
stringify(value);
}
});
},
}
},

{
Expand All @@ -44,7 +44,7 @@ export default [
stringify(value);
}
});
},
}
},

{
Expand All @@ -62,7 +62,7 @@ export default [
stringify(value);
}
});
},
}
},

{
Expand All @@ -80,7 +80,7 @@ export default [
parse(string);
}
});
},
}
},

{
Expand All @@ -98,7 +98,7 @@ export default [
parse(string);
}
});
},
}
},

{
Expand All @@ -116,6 +116,6 @@ export default [
parse(string);
}
});
},
},
}
}
];
6 changes: 2 additions & 4 deletions benchmarking/compare/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const is_jj = execSync('git for-each-ref --count=1 refs/jj/').length > 0;
const current_ref = exec(
is_jj
? 'jj show --no-patch --template change_id'
: 'git symbolic-ref --short -q HEAD || git rev-parse --short HEAD',
: 'git symbolic-ref --short -q HEAD || git rev-parse --short HEAD'
);

/** @type {(branch: string) => void} */
Expand Down Expand Up @@ -95,9 +95,7 @@ for (let i = 0; i < results[0].length; i += 1) {
const SIZE = 20;
const n = Math.round(SIZE * (time / max));

console.log(
`${char(b)}: ${'◼'.repeat(n)}${' '.repeat(SIZE - n)} ${time.toFixed(2)}ms`,
);
console.log(`${char(b)}: ${'◼'.repeat(n)}${' '.repeat(SIZE - n)} ${time.toFixed(2)}ms`);
});
console.groupEnd();
}
Expand Down
12 changes: 6 additions & 6 deletions benchmarking/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const filter_fn = filters.length ? (b) => filters.some((f) => b.label.includes(f
const suites = [
{
name: 'TypedArray benchmarks',
benchmarks: typed_array_benchmarks.filter(filter_fn),
},
benchmarks: typed_array_benchmarks.filter(filter_fn)
}
].filter((suite) => suite.benchmarks.length > 0);

if (suites.length === 0) {
Expand Down Expand Up @@ -39,7 +39,7 @@ try {
console.log(
pad_right('Benchmark', COLUMN_WIDTHS[0]) +
pad_left('Time', COLUMN_WIDTHS[1]) +
pad_left('GC time', COLUMN_WIDTHS[2]),
pad_left('GC time', COLUMN_WIDTHS[2])
);
console.log('='.repeat(TOTAL_WIDTH));

Expand All @@ -48,7 +48,7 @@ try {
console.log(
pad_right(benchmark.label, COLUMN_WIDTHS[0]) +
pad_left(results.time.toFixed(2), COLUMN_WIDTHS[1]) +
pad_left(results.gc_time.toFixed(2), COLUMN_WIDTHS[2]),
pad_left(results.gc_time.toFixed(2), COLUMN_WIDTHS[2])
);
total_time += results.time;
total_gc_time += results.gc_time;
Expand All @@ -60,7 +60,7 @@ try {
console.log(
pad_right('suite', COLUMN_WIDTHS[0]) +
pad_left(suite_time.toFixed(2), COLUMN_WIDTHS[1]) +
pad_left(suite_gc_time.toFixed(2), COLUMN_WIDTHS[2]),
pad_left(suite_gc_time.toFixed(2), COLUMN_WIDTHS[2])
);
console.log('='.repeat(TOTAL_WIDTH));
}
Expand All @@ -74,5 +74,5 @@ console.log('');
console.log(
pad_right('total', COLUMN_WIDTHS[0]) +
pad_left(total_time.toFixed(2), COLUMN_WIDTHS[1]) +
pad_left(total_gc_time.toFixed(2), COLUMN_WIDTHS[2]),
pad_left(total_gc_time.toFixed(2), COLUMN_WIDTHS[2])
);
15 changes: 3 additions & 12 deletions src/base64.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,7 @@ export function decode_legacy(base64) {
}

const native = typeof Uint8Array.fromBase64 === 'function';
const buffer =
typeof process === 'object' && process.versions?.node !== undefined;
const buffer = typeof process === 'object' && process.versions?.node !== undefined;

export const encode64 = native
? encode_native
: buffer
? encode_buffer
: encode_legacy;
export const decode64 = native
? decode_native
: buffer
? decode_buffer
: decode_legacy;
export const encode64 = native ? encode_native : buffer ? encode_buffer : encode_legacy;
export const decode64 = native ? decode_native : buffer ? decode_buffer : decode_legacy;
12 changes: 5 additions & 7 deletions src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,7 @@ export function unflatten(parsed, revivers) {
if (typeof value[0] === 'string') {
const type = value[0];

const reviver =
revivers && Object.hasOwn(revivers, type)
? revivers[type]
: undefined;
const reviver = revivers && Object.hasOwn(revivers, type) ? revivers[type] : undefined;

if (reviver) {
let i = value[1];
Expand Down Expand Up @@ -165,9 +162,10 @@ export function unflatten(parsed, revivers) {
const TypedArrayConstructor = globalThis[type];
const buffer = hydrate(value[1]);

hydrated[index] = value[2] !== undefined
? new TypedArrayConstructor(buffer, value[2], value[3])
: new TypedArrayConstructor(buffer);
hydrated[index] =
value[2] !== undefined
? new TypedArrayConstructor(buffer, value[2], value[3])
: new TypedArrayConstructor(buffer);

break;
}
Expand Down
20 changes: 4 additions & 16 deletions src/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function stringify(value, reducers) {
if (thing === -Infinity) return NEGATIVE_INFINITY;
if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO;

if (indexes.has(thing)) return indexes.get(thing);
if (indexes.has(thing)) return /** @type {number} */ (indexes.get(thing));

const index = p++;
indexes.set(thing, index);
Expand Down Expand Up @@ -205,9 +205,7 @@ export function stringify(value, reducers) {
str = '["Map"';

for (const [key, value] of thing) {
keys.push(
`.get(${is_primitive(key) ? stringify_primitive(key) : '...'})`
);
keys.push(`.get(${is_primitive(key) ? stringify_primitive(key) : '...'})`);
str += `,${flatten(key)},${flatten(value)}`;
keys.pop();
}
Expand Down Expand Up @@ -263,21 +261,11 @@ export function stringify(value, reducers) {

default:
if (!is_plain_object(thing)) {
throw new DevalueError(
`Cannot stringify arbitrary non-POJOs`,
keys,
thing,
value
);
throw new DevalueError(`Cannot stringify arbitrary non-POJOs`, keys, thing, value);
}

if (enumerable_symbols(thing).length > 0) {
throw new DevalueError(
`Cannot stringify POJOs with symbolic keys`,
keys,
thing,
value
);
throw new DevalueError(`Cannot stringify POJOs with symbolic keys`, keys, thing, value);
}

if (Object.getPrototypeOf(thing) === null) {
Expand Down
14 changes: 13 additions & 1 deletion src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Float16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
export type TypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Float16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array
| BigInt64Array
| BigUint64Array;
56 changes: 13 additions & 43 deletions src/uneval.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ export function uneval(value, replacer) {

case 'Map':
for (const [key, value] of thing) {
keys.push(
`.get(${is_primitive(key) ? stringify_primitive(key) : '...'})`
);
keys.push(`.get(${is_primitive(key) ? stringify_primitive(key) : '...'})`);
walk(value);
keys.pop();
}
Expand Down Expand Up @@ -116,21 +114,11 @@ export function uneval(value, replacer) {

default:
if (!is_plain_object(thing)) {
throw new DevalueError(
`Cannot stringify arbitrary non-POJOs`,
keys,
thing,
value
);
throw new DevalueError(`Cannot stringify arbitrary non-POJOs`, keys, thing, value);
}

if (enumerable_symbols(thing).length > 0) {
throw new DevalueError(
`Cannot stringify POJOs with symbolic keys`,
keys,
thing,
value
);
throw new DevalueError(`Cannot stringify POJOs with symbolic keys`, keys, thing, value);
}

for (const key of Object.keys(thing)) {
Expand Down Expand Up @@ -188,9 +176,7 @@ export function uneval(value, replacer) {
return `Object(${stringify(thing.valueOf())})`;

case 'RegExp':
return `new RegExp(${stringify_string(thing.source)}, "${
thing.flags
}")`;
return `new RegExp(${stringify_string(thing.source)}, "${thing.flags}")`;

case 'Date':
return `new Date(${thing.getTime()})`;
Expand Down Expand Up @@ -260,12 +246,10 @@ export function uneval(value, replacer) {
const d = String(thing.length).length;

const hole_cost = thing.length + 2;
const sparse_cost = (25 + d) + population * (d + 2);
const sparse_cost = 25 + d + population * (d + 2);

if (hole_cost > sparse_cost) {
const entries = populated_keys
.map((k) => `${k}:${stringify(thing[k])}`)
.join(',');
const entries = populated_keys.map((k) => `${k}:${stringify(thing[k])}`).join(',');
return `Object.assign(Array(${thing.length}),{${entries}})`;
}

Expand Down Expand Up @@ -333,14 +317,10 @@ export function uneval(value, replacer) {

default:
const keys = Object.keys(thing);
const obj = keys
.map((key) => `${safe_key(key)}:${stringify(thing[key])}`)
.join(',');
const obj = keys.map((key) => `${safe_key(key)}:${stringify(thing[key])}`).join(',');
const proto = Object.getPrototypeOf(thing);
if (proto === null) {
return keys.length > 0
? `{${obj},__proto__:null}`
: `{__proto__:null}`;
return keys.length > 0 ? `{${obj},__proto__:null}` : `{__proto__:null}`;
}

return `{${obj}}`;
Expand Down Expand Up @@ -415,28 +395,20 @@ export function uneval(value, replacer) {
break;

case 'ArrayBuffer':
values.push(
`new Uint8Array([${new Uint8Array(thing).join(',')}]).buffer`
);
values.push(`new Uint8Array([${new Uint8Array(thing).join(',')}]).buffer`);
break;

default:
values.push(
Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}'
);
values.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
Object.keys(thing).forEach((key) => {
statements.push(
`${name}${safe_prop(key)}=${stringify(thing[key])}`
);
statements.push(`${name}${safe_prop(key)}=${stringify(thing[key])}`);
});
}
});

statements.push(`return ${str}`);

return `(function(${params.join(',')}){${statements.join(
';'
)}}(${values.join(',')}))`;
return `(function(${params.join(',')}){${statements.join(';')}}(${values.join(',')}))`;
} else {
return str;
}
Expand Down Expand Up @@ -466,9 +438,7 @@ function escape_unsafe_chars(str) {

/** @param {string} key */
function safe_key(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key)
? key
: escape_unsafe_chars(JSON.stringify(key));
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escape_unsafe_chars(JSON.stringify(key));
}

/** @param {string} key */
Expand Down
10 changes: 3 additions & 7 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,10 @@ export class DevalueError extends Error {

/** @param {any} thing */
export function is_primitive(thing) {
return Object(thing) !== thing;
return thing === null || (typeof thing !== 'object' && typeof thing !== 'function');
}

const object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(
Object.prototype
)
const object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(Object.prototype)
.sort()
.join('\0');

Expand Down Expand Up @@ -79,9 +77,7 @@ function get_escaped_char(char) {
case '\u2029':
return '\\u2029';
default:
return char < ' '
? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
: '';
return char < ' ' ? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}` : '';
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ test('handles a single-element array with non-numeric property', () => {
test('handles array properties pretending to be indices', () => {
const arr = ['a', 'b'];
arr[-1] = 'negative index';
arr[2**32 - 1] = 'too large index';
arr[2 ** 32 - 1] = 'too large index';
assert.equal(valid_array_indices(arr), ['0', '1']);
})
});

test.run();
Loading
Loading