Skip to content
Open
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
17 changes: 15 additions & 2 deletions packages/csv-stringify/lib/api/normalize_options.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,21 @@ const normalize_options = function (opts) {
// Normalize option `cast`
if (options.cast === undefined || options.cast === null) {
options.cast = {};
} else {
// todo
} else if (
typeof options.cast === "object" ||
typeof options.cast === "function"
) {
options.cast = {
...options.cast,
bigint: options.cast.bigint,
boolean: options.cast.boolean,
date: options.cast.date,
number: options.cast.number,
object: options.cast.object,
string: options.cast.string,
null: options.cast.null,
undefined: options.cast.undefined,
};
}
// Normalize option cast.bigint
if (options.cast.bigint === undefined || options.cast.bigint === null) {
Expand Down
44 changes: 44 additions & 0 deletions packages/csv-stringify/test/option.cast.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,52 @@
import "should";
import assert from "node:assert/strict";
import { stringify } from "../lib/index.js";
import { stringify as stringifySync } from "../lib/sync.js";

describe("Option `cast`", function () {
describe("configuration", function () {
for (const frozen of [false, true]) {
it(`preserves ${frozen ? "frozen" : "mutable"} options in the sync API`, function () {
const string = (value) => value.toUpperCase();
const cast = { string, number: null };
if (frozen) Object.freeze(cast);
for (let i = 0; i < 2; i++) {
assert.equal(stringifySync([["value", 42]], { cast }), "VALUE,42\n");
}
assert.deepEqual(cast, { string, number: null });
});

it(`preserves ${frozen ? "frozen" : "mutable"} options in the callback API`, function (next) {
const string = (value) => value.toUpperCase();
const cast = { string };
if (frozen) Object.freeze(cast);
stringify([["value", 42]], { cast }, (err, output) => {
if (err) return next(err);
assert.equal(output, "VALUE,42\n");
assert.deepEqual(cast, { string });
next();
});
});
}

it("preserves inherited and non-enumerable custom casters", function () {
const cast = Object.create({ string: (value) => value.toUpperCase() });
Object.defineProperty(cast, "number", { value: () => "number" });
assert.equal(stringifySync([["value", 42]], { cast }), "VALUE,number\n");
});

it("preserves custom null and undefined casters", function () {
const cast = {
null: () => "null",
undefined: () => "missing",
};
assert.equal(
stringifySync([[null, undefined]], { cast }),
"null,missing\n",
);
});
});

describe("udf", function () {
it("boolean must return a string", function (next) {
stringify(
Expand Down