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

dsv type option #301

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
31 changes: 29 additions & 2 deletions src/fileAttachment.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,38 @@ async function remote_fetch(file) {
return response;
}

async function dsv(file, delimiter, {array = false, typed = false} = {}) {
function asTyper(type) {
if (typeof type === "function") {
return type;
}
switch (`${type}`) {
case "number": return Number;
case "string": return String;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in autoType the string gets trimmed. probably not something to include in casting, but will be different

case "boolean": return Boolean;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this differs from autotype in that it will not turn "false" into false. is that ok?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, no, that wasn’t intentional.

case "date": return NewDate;
default: throw new Error(`unknown type: ${type}`);
}
}

function NewDate(value) {
return new Date(value);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we want to do the timezone workaround for Safari?

}

function asTypers(types) {
const typers = Object.create(null);
for (const key in types) typers[key] = asTyper(types[key]);
return (d, i) => {
const object = Object.create(null);
for (const key in typers) object[key] = typers[key](d[key], i);
return object;
};
}

async function dsv(file, delimiter, {array = false, type, typed = false} = {}) {
const text = await file.text();
return (delimiter === "\t"
? (array ? tsvParseRows : tsvParse)
: (array ? csvParseRows : csvParse))(text, typed && autoType);
: (array ? csvParseRows : csvParse))(text, type ? asTypers(type) : typed ? autoType : null);
}

export class AbstractFile {
Expand Down