@thi.ng/csv
Version:
Customizable, transducer-based CSV parser/object mapper and transformer
49 lines (48 loc) • 1.35 kB
JavaScript
import { padLeft } from "@thi.ng/strings/pad-left";
import { maybeParseFloat, maybeParseInt } from "@thi.ng/strings/parse";
import { percent as $percent } from "@thi.ng/strings/percent";
const upper = (x) => x.toUpperCase();
const lower = (x) => x.toLowerCase();
const json = (defaultVal) => (x) => {
try {
return JSON.parse(x);
} catch (e) {
return defaultVal;
}
};
const float = (defaultVal = 0) => (x) => maybeParseFloat(x, defaultVal);
const int = (defaultVal = 0) => (x) => maybeParseInt(x, defaultVal, 10);
const hex = (defaultVal = 0) => (x) => maybeParseInt(x, defaultVal, 16);
const percent = (x) => maybeParseFloat(x) * 0.01;
const epoch = (defaultVal = 0) => (x) => {
const res = Date.parse(x);
return isNaN(res) ? defaultVal : res;
};
const date = (defaultVal) => (x) => {
const epoch2 = Date.parse(x);
if (isNaN(epoch2)) return defaultVal;
const res = /* @__PURE__ */ new Date();
res.setTime(epoch2);
return res;
};
const url = (x) => new URL(x);
const oneOf = (mappings, defaultVal) => (x) => mappings[x] ?? defaultVal;
const zeroPad = (digits) => padLeft(digits, "0");
const formatFloat = (prec = 2) => (x) => x.toFixed(prec);
const formatPercent = $percent;
export {
date,
epoch,
float,
formatFloat,
formatPercent,
hex,
int,
json,
lower,
oneOf,
percent,
upper,
url,
zeroPad
};