nodejs-polars
Version:
Polars: Blazingly fast DataFrames in Rust, Python, Node.js, R and SQL
825 lines (824 loc) • 32.8 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.exprToLitOrExpr = exports.Expr = exports._Expr = void 0;
exports.datetime = datetime;
exports.date = date;
exports.duration = duration;
const dt = __importStar(require("./datetime"));
const list = __importStar(require("./list"));
const str = __importStar(require("./string"));
const struct = __importStar(require("./struct"));
const types_1 = require("node:util/types");
const error_1 = require("../../error");
const polars_internal_1 = __importDefault(require("../../internals/polars_internal"));
const series_1 = require("../../series");
const utils_1 = require("../../utils");
/** @ignore */
const _Expr = (_expr) => {
const unwrap = (method, ...args) => {
return _expr[method](...args);
};
const wrap = (method, ...args) => {
return (0, exports._Expr)(unwrap(method, ...args));
};
const wrapExprArg = (method, lit = false) => (other) => {
const expr = (0, exports.exprToLitOrExpr)(other, lit).inner();
return wrap(method, expr);
};
const rolling = (method) => (opts, weights, minPeriods, center) => {
const windowSize = opts?.["windowSize"] ?? (typeof opts === "number" ? opts : null);
if (windowSize === null) {
throw new Error("window size is required");
}
const callOpts = {
windowSize: windowSize,
weights: opts?.["weights"] ?? weights,
minPeriods: opts?.["minPeriods"] ?? minPeriods ?? windowSize,
center: opts?.["center"] ?? center ?? false,
};
return wrap(method, callOpts);
};
return {
_expr,
[Symbol.toStringTag]() {
return "Expr";
},
[utils_1.INSPECT_SYMBOL]() {
return _expr.toString();
},
serialize(format) {
return _expr.serialize(format);
},
toString() {
return _expr.toString();
},
toJSON(...args) {
// this is passed by `JSON.stringify` when calling `toJSON()`
if (args[0] === "") {
return _expr.toJs();
}
return _expr.serialize("json").toString();
},
get str() {
return str.ExprStringFunctions(_expr);
},
/** List functions are now available under the `list` namespace. The `lst` namespace is deprecated and will be removed in a future version. See the `list` namespace for more details.
* @deprecated *since 0.25.0 use list instead to match Polars core
*/
get lst() {
return list.ExprListFunctions(_expr);
},
get list() {
return list.ExprListFunctions(_expr);
},
get dt() {
return dt.ExprDateTimeFunctions(_expr);
},
get struct() {
return struct.ExprStructFunctions(_expr);
},
abs() {
return (0, exports._Expr)(_expr.abs());
},
alias(name) {
return (0, exports._Expr)(_expr.alias(name));
},
all(ignoreNulls = true) {
ignoreNulls = ignoreNulls?.ignoreNulls ?? ignoreNulls;
return (0, exports._Expr)(_expr.all(ignoreNulls));
},
inner() {
return _expr;
},
and(other) {
const expr = (0, exports.exprToLitOrExpr)(other, false).inner();
return (0, exports._Expr)(_expr.and(expr));
},
any(ignoreNulls = true) {
ignoreNulls = ignoreNulls?.ignoreNulls ?? ignoreNulls;
return (0, exports._Expr)(_expr.any(ignoreNulls));
},
arccos() {
return (0, exports._Expr)(_expr.arccos());
},
arccosh() {
return (0, exports._Expr)(_expr.arccosh());
},
arcsin() {
return (0, exports._Expr)(_expr.arcsin());
},
arcsinh() {
return (0, exports._Expr)(_expr.arcsinh());
},
arctan() {
return (0, exports._Expr)(_expr.arctan());
},
arctan2(other) {
const expr = (0, exports.exprToLitOrExpr)(other, false).inner();
return (0, exports._Expr)(_expr.arctan2(expr));
},
arctanh() {
return (0, exports._Expr)(_expr.arctanh());
},
argMax() {
return (0, exports._Expr)(_expr.argMax());
},
argMin() {
return (0, exports._Expr)(_expr.argMin());
},
argSort(descending = false, nullsLast = false) {
nullsLast = descending?.nullsLast ?? nullsLast;
descending = descending?.descending ?? descending;
return (0, exports._Expr)(_expr.argSort(descending, nullsLast));
},
argUnique() {
return (0, exports._Expr)(_expr.argUnique());
},
as(name) {
return (0, exports._Expr)(_expr.alias(name));
},
backwardFill() {
return (0, exports._Expr)(_expr.backwardFill());
},
cast(dtype, strict = false) {
return (0, exports._Expr)(_expr.cast(dtype, strict));
},
ceil() {
return (0, exports._Expr)(_expr.ceil());
},
clip(arg, max) {
if (typeof arg === "number") {
return (0, exports._Expr)(_expr.clip((0, exports.exprToLitOrExpr)(arg)._expr, (0, exports.exprToLitOrExpr)(max)._expr));
}
return (0, exports._Expr)(_expr.clip((0, exports.exprToLitOrExpr)(arg.min)._expr, (0, exports.exprToLitOrExpr)(arg.max)._expr));
},
cos() {
return (0, exports._Expr)(_expr.cos());
},
cosh() {
return (0, exports._Expr)(_expr.cosh());
},
cot() {
return (0, exports._Expr)(_expr.cot());
},
count() {
return (0, exports._Expr)(_expr.count());
},
cumCount(reverse = false) {
reverse = reverse?.reverse ?? reverse;
return (0, exports._Expr)(_expr.cumCount(reverse));
},
cumMax(reverse = false) {
reverse = reverse?.reverse ?? reverse;
return (0, exports._Expr)(_expr.cumMax(reverse));
},
cumMin(reverse = false) {
reverse = reverse?.reverse ?? reverse;
return (0, exports._Expr)(_expr.cumMin(reverse));
},
cumProd(reverse = false) {
reverse = reverse?.reverse ?? reverse;
return (0, exports._Expr)(_expr.cumProd(reverse));
},
cumSum(reverse = false) {
reverse = reverse?.reverse ?? reverse;
return (0, exports._Expr)(_expr.cumSum(reverse));
},
diff(n, nullBehavior = "ignore") {
if (typeof n === "number") {
return (0, exports._Expr)(_expr.diff((0, exports.exprToLitOrExpr)(n, false), nullBehavior));
}
return (0, exports._Expr)(_expr.diff((0, exports.exprToLitOrExpr)(n.n, false), n.nullBehavior));
},
degrees() {
return (0, exports._Expr)(_expr.degrees());
},
dot(other) {
const expr = (0, exports.exprToLitOrExpr)(other, false).inner();
return (0, exports._Expr)(_expr.dot(expr));
},
dropNans() {
return (0, exports._Expr)(_expr.dropNans());
},
dropNulls() {
return (0, exports._Expr)(_expr.dropNulls());
},
entropy(base = Math.E, normalize = true) {
if (typeof base === "object" && base !== null) {
normalize = base.normalize ?? normalize;
base = base.base ?? Math.E;
}
return (0, exports._Expr)(_expr.entropy(base, normalize));
},
ewmMean(opts, adjust, minPeriods, bias, ignoreNulls) {
if (opts) {
if (typeof opts === "number") {
return wrap("ewmMean", opts, adjust ?? true, minPeriods ?? 1, bias ?? false, ignoreNulls ?? true);
}
return wrap("ewmMean", opts.alpha ?? 0.5, opts.adjust ?? true, opts.minPeriods ?? 1, opts.bias ?? false, opts.ignoreNulls ?? true);
}
return wrap("ewmMean", 0.5, true, 1, false, true);
},
ewmStd(opts, adjust, minPeriods, bias, ignoreNulls) {
if (opts) {
if (typeof opts === "number") {
return wrap("ewmStd", opts, adjust ?? true, minPeriods ?? 1, bias ?? false, ignoreNulls ?? true);
}
return wrap("ewmStd", opts.alpha ?? 0.5, opts.adjust ?? true, opts.minPeriods ?? 1, opts.bias ?? false, opts.ignoreNulls ?? true);
}
return wrap("ewmStd", 0.5, true, 1, false, true);
},
ewmVar(opts, adjust, minPeriods, bias, ignoreNulls) {
if (opts) {
if (typeof opts === "number") {
return wrap("ewmVar", opts, adjust ?? true, minPeriods ?? 1, bias ?? false, ignoreNulls ?? true);
}
return wrap("ewmVar", opts.alpha ?? 0.5, opts.adjust ?? true, opts.minPeriods ?? 1, opts.bias ?? false, opts.ignoreNulls ?? true);
}
return wrap("ewmVar", 0.5, true, 1, false, true);
},
exclude(...columns) {
return (0, exports._Expr)(_expr.exclude(columns.flat(2)));
},
explode() {
return (0, exports._Expr)(_expr.explode());
},
exp() {
return (0, exports._Expr)(_expr.exp());
},
extendConstant(o, n) {
if (n !== null && typeof n === "number") {
return (0, exports._Expr)(_expr.extendConstant(o, n));
}
return (0, exports._Expr)(_expr.extendConstant(o.value, o.n));
},
fillNan(other) {
const expr = (0, exports.exprToLitOrExpr)(other, true).inner();
return (0, exports._Expr)(_expr.fillNan(expr));
},
fillNull(fillValue, limit) {
if (["backward", "forward", "mean", "min", "max", "zero", "one"].includes(fillValue)) {
return (0, exports._Expr)(_expr.fillNullWithStrategy(fillValue, limit ?? null));
}
const expr = (0, exports.exprToLitOrExpr)(fillValue).inner();
return (0, exports._Expr)(_expr.fillNull(expr));
},
filter(predicate) {
const expr = (0, exports.exprToLitOrExpr)(predicate).inner();
return (0, exports._Expr)(_expr.filter(expr));
},
first() {
return (0, exports._Expr)(_expr.first());
},
flatten() {
return (0, exports._Expr)(_expr.explode());
},
floor() {
return (0, exports._Expr)(_expr.floor());
},
forwardFill() {
return (0, exports._Expr)(_expr.forwardFill());
},
gather(indices) {
indices = indices?.index ?? indices;
if (Array.isArray(indices)) {
indices = polars_internal_1.default.litSeries((0, series_1.Series)("", indices, polars_internal_1.default.Int64).inner());
}
else {
indices = (0, exports.exprToLitOrExpr)(indices).inner();
}
return wrap("gather", indices);
},
gatherEvery(n, offset = 0) {
return (0, exports._Expr)(_expr.gatherEvery(n, offset));
},
hash(obj = 0, k1 = 1, k2 = 2, k3 = 3) {
if (typeof obj === "number" || typeof obj === "bigint") {
return wrap("hash", BigInt(obj), BigInt(k1), BigInt(k2), BigInt(k3));
}
const o = { k0: obj, k1: k1, k2: k2, k3: k3, ...obj };
return wrap("hash", BigInt(o.k0), BigInt(o.k1), BigInt(o.k2), BigInt(o.k3));
},
mapBatches(fnOrOpts, options) {
let fn;
let opts;
if (typeof fnOrOpts === "function") {
fn = fnOrOpts;
opts = options ?? {};
}
else {
fn = fnOrOpts.fn;
opts = fnOrOpts;
}
const adapter = (native) => {
const input = (0, series_1._Series)(native);
const out = fn(input);
if (series_1.Series.isSeries(out)) {
return out.inner();
}
if (opts.returnsScalar && isScalarValue(out)) {
const shape = [out === undefined ? null : out];
const scalarSeries = opts.returnType === undefined
? (0, series_1.Series)(input.name, shape)
: (0, series_1.Series)(input.name, shape, opts.returnType);
return scalarSeries.inner();
}
throw new error_1.InvalidOperationError("mapBatches callback must return a polars ", "Series");
};
return (0, exports._Expr)(_expr.mapBatches(adapter, opts));
},
head(length) {
if (typeof length === "number") {
return wrap("head", length);
}
return wrap("head", length.length);
},
implode() {
return (0, exports._Expr)(_expr.implode());
},
interpolate(method = "linear") {
return (0, exports._Expr)(_expr.interpolate(method));
},
isDuplicated() {
return (0, exports._Expr)(_expr.isDuplicated());
},
isFinite() {
return (0, exports._Expr)(_expr.isFinite());
},
isInfinite() {
return (0, exports._Expr)(_expr.isInfinite());
},
isFirstDistinct() {
return (0, exports._Expr)(_expr.isFirstDistinct());
},
isNan() {
return (0, exports._Expr)(_expr.isNan());
},
isNotNan() {
return (0, exports._Expr)(_expr.isNotNan());
},
isNotNull() {
return (0, exports._Expr)(_expr.isNotNull());
},
isNull() {
return (0, exports._Expr)(_expr.isNull());
},
isUnique() {
return (0, exports._Expr)(_expr.isUnique());
},
isIn(other, nullsEquals = false) {
if (Array.isArray(other)) {
other = polars_internal_1.default.lit((0, series_1.Series)(other).inner());
}
else {
other = (0, exports.exprToLitOrExpr)(other, false).inner();
}
return wrap("isIn", other, nullsEquals);
},
keepName() {
return (0, exports._Expr)(_expr.keepName());
},
kurtosis(obj, bias = true) {
const fisher = obj?.["fisher"] ?? (typeof obj === "boolean" ? obj : true);
bias = obj?.["bias"] ?? bias;
return (0, exports._Expr)(_expr.kurtosis(fisher, bias));
},
last() {
return (0, exports._Expr)(_expr.last());
},
log1p() {
return (0, exports._Expr)(_expr.log1P());
},
log(base) {
return (0, exports._Expr)(_expr.log(base ?? Math.E));
},
lowerBound() {
return (0, exports._Expr)(_expr.lowerBound());
},
peakMax() {
return (0, exports._Expr)(_expr.peakMax());
},
peakMin() {
return (0, exports._Expr)(_expr.peakMin());
},
max() {
return (0, exports._Expr)(_expr.max());
},
mean() {
return (0, exports._Expr)(_expr.mean());
},
median() {
return (0, exports._Expr)(_expr.median());
},
min() {
return (0, exports._Expr)(_expr.min());
},
mode() {
return (0, exports._Expr)(_expr.mode());
},
not() {
return (0, exports._Expr)(_expr.not());
},
nUnique() {
return (0, exports._Expr)(_expr.nUnique());
},
nullCount() {
return (0, exports._Expr)(_expr.nullCount());
},
or(other) {
const expr = (0, exports.exprToLitOrExpr)(other).inner();
return (0, exports._Expr)(_expr.or(expr));
},
over(...exprs) {
const partitionBy = (0, utils_1.selectionToExprList)(exprs, false);
return wrap("over", partitionBy);
},
pctChange(n = 1) {
n = n?.n ?? n;
return (0, exports._Expr)(_expr.pctChange((0, exports.exprToLitOrExpr)(n, false)));
},
pow(exponent) {
return (0, exports._Expr)(_expr.pow(exponent?.exponent ?? exponent));
},
prefix(prefix) {
return (0, exports._Expr)(_expr.prefix(prefix));
},
product() {
return (0, exports._Expr)(_expr.product());
},
quantile(quantile, interpolation = "nearest") {
if (exports.Expr.isExpr(quantile)) {
quantile = quantile._expr;
}
else {
quantile = polars_internal_1.default.lit(quantile);
}
return (0, exports._Expr)(_expr.quantile(quantile, interpolation));
},
radians() {
return (0, exports._Expr)(_expr.radians());
},
rank(method = "average", descending = false) {
return (0, exports._Expr)(_expr.rank(method?.method ?? method, method?.descending ?? descending));
},
reinterpret(signed = true) {
signed = signed?.signed ?? signed;
return (0, exports._Expr)(_expr.reinterpret(signed));
},
repeatBy(expr) {
const e = (0, exports.exprToLitOrExpr)(expr, false)._expr;
return (0, exports._Expr)(_expr.repeatBy(e));
},
reshape(dims) {
return (0, exports._Expr)(_expr.reshape(dims));
},
replace(old, newValue) {
let oldIn = old;
let newIn = newValue;
if (old && typeof old === "object" && !Array.isArray(old)) {
oldIn = Object.keys(old["old"]);
newIn = Object.values(old["old"]);
}
return (0, exports._Expr)(_expr.replace((0, exports.exprToLitOrExpr)(oldIn)._expr, (0, exports.exprToLitOrExpr)(newIn)._expr));
},
replaceStrict(old, newValue, defaultValue, returnDtype) {
let oldIn = old;
let newIn = newValue;
let defIn = defaultValue;
if (old && typeof old === "object" && !Array.isArray(old)) {
oldIn = Object.keys(old["old"]);
newIn = Object.values(old["old"]);
defIn = old["default_"];
}
return (0, exports._Expr)(_expr.replaceStrict((0, exports.exprToLitOrExpr)(oldIn)._expr, (0, exports.exprToLitOrExpr)(newIn)._expr, defIn ? (0, exports.exprToLitOrExpr)(defIn)._expr : undefined, returnDtype));
},
reverse() {
return (0, exports._Expr)(_expr.reverse());
},
rollingMax: rolling("rollingMax"),
rollingMean: rolling("rollingMean"),
rollingMin: rolling("rollingMin"),
rollingSum: rolling("rollingSum"),
rollingStd: rolling("rollingStd"),
rollingVar: rolling("rollingVar"),
rollingMedian: rolling("rollingMedian"),
rollingQuantile(val, _interpolation, windowSize, weights, minPeriods, center, by, closedWindow, warnIfUnsorted) {
if (typeof val === "number") {
if (windowSize == null) {
throw new Error("window size is required");
}
return wrap("rollingQuantile", val, _interpolation ?? "nearest", windowSize, weights ?? null, minPeriods ?? windowSize, center ?? false, by, closedWindow, warnIfUnsorted ?? true);
}
windowSize =
val?.["windowSize"] ?? (typeof val === "number" ? val : null);
if (windowSize === null) {
throw new Error("window size is required");
}
return wrap("rollingQuantile", val.quantile, val.interpolation ?? "nearest", windowSize, val?.["weights"] ?? weights ?? null, val?.["minPeriods"] ?? minPeriods ?? windowSize, val?.["center"] ?? center ?? false, val?.["by"] ?? by, closedWindow, val?.["warnIfUnsorted"] ?? warnIfUnsorted ?? true);
},
rollingSkew(val, bias = true) {
if (typeof val === "number") {
return wrap("rollingSkew", val, bias);
}
return wrap("rollingSkew", val.windowSize, val.bias ?? bias);
},
round(decimals, mode) {
return (0, exports._Expr)(_expr.round(decimals?.decimals ?? decimals, decimals?.mode ?? mode ?? "halftoeven"));
},
sample(opts, frac, withReplacement = false, seed, shuffle = false) {
if (opts?.n !== undefined || opts?.frac !== undefined) {
return this.sample(opts.n, opts.frac, opts.withReplacement, opts.seed, opts.shuffle ?? shuffle);
}
if (typeof opts === "number") {
return wrap("sampleN", (0, exports.exprToLitOrExpr)(opts), withReplacement, shuffle, seed);
}
if (typeof frac === "number") {
return wrap("sampleFrac", (0, exports.exprToLitOrExpr)(frac), withReplacement, shuffle, seed);
}
throw new TypeError("must specify either 'frac' or 'n'");
},
shift(periods) {
periods = periods?.periods ?? periods;
return (0, exports._Expr)(_expr.shift((0, exports.exprToLitOrExpr)(periods)._expr));
},
shiftAndFill(optOrPeriods, fillValue) {
if (typeof optOrPeriods === "number") {
return wrap("shiftAndFill", optOrPeriods, fillValue);
}
return wrap("shiftAndFill", optOrPeriods.periods, optOrPeriods.fillValue);
},
shuffle(seed) {
seed = seed?.seed ?? seed;
if (seed === undefined || seed === null) {
seed = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
}
return (0, exports._Expr)(_expr.shuffle(BigInt(seed)));
},
skew(bias) {
return wrap("skew", bias?.bias ?? bias ?? true);
},
sin() {
return (0, exports._Expr)(_expr.sin());
},
sinh() {
return (0, exports._Expr)(_expr.sinh());
},
slice(arg, len) {
if (typeof arg === "number") {
return wrap("slice", polars_internal_1.default.lit(arg), polars_internal_1.default.lit(len));
}
return wrap("slice", polars_internal_1.default.lit(arg.offset), polars_internal_1.default.lit(arg.length));
},
sort(descending = false, nullsLast = false, maintainOrder = false) {
if (typeof descending === "boolean") {
return wrap("sortWith", descending, nullsLast, false, maintainOrder);
}
return wrap("sortWith", descending?.descending ?? false, descending?.nullsLast ?? nullsLast, false, descending?.maintainOrder ?? maintainOrder);
},
sortBy(arg, descending = false) {
if (arg?.by !== undefined) {
descending = arg?.descending ?? false;
arg = arg.by;
}
descending = Array.isArray(descending)
? descending.flat()
: [descending];
const by = (0, utils_1.selectionToExprList)(arg, false);
return wrap("sortBy", by, descending);
},
std() {
return (0, exports._Expr)(_expr.std());
},
suffix(suffix) {
return (0, exports._Expr)(_expr.suffix(suffix));
},
sum() {
return (0, exports._Expr)(_expr.sum());
},
tail(length) {
length = length?.length ?? length;
return (0, exports._Expr)(_expr.tail(length));
},
tan() {
return (0, exports._Expr)(_expr.tan());
},
tanh() {
return (0, exports._Expr)(_expr.tanh());
},
unique(opt) {
if (opt || opt?.maintainOrder) {
return wrap("uniqueStable");
}
return wrap("unique");
},
uniqueCounts() {
return (0, exports._Expr)(_expr.uniqueCounts());
},
upperBound() {
return (0, exports._Expr)(_expr.upperBound());
},
valueCounts(sort = false, parallel = false, name, normalize = false) {
name = name ?? (normalize ? "proportion" : "count");
return (0, exports._Expr)(_expr.valueCounts(sort, parallel, name, normalize));
},
var() {
return (0, exports._Expr)(_expr.var());
},
toPhysical() {
return (0, exports._Expr)(_expr.toPhysical());
},
add: wrapExprArg("add"),
sub: wrapExprArg("sub"),
div: wrapExprArg("div"),
mul: wrapExprArg("mul"),
rem: wrapExprArg("rem"),
plus: wrapExprArg("add"),
minus: wrapExprArg("sub"),
divideBy: wrapExprArg("div"),
multiplyBy: wrapExprArg("mul"),
modulo: wrapExprArg("rem"),
eq: wrapExprArg("eq"),
equals: wrapExprArg("eq"),
gtEq: wrapExprArg("gtEq"),
greaterThanEquals: wrapExprArg("gtEq"),
gt: wrapExprArg("gt"),
greaterThan: wrapExprArg("gt"),
ltEq: wrapExprArg("ltEq"),
lessThanEquals: wrapExprArg("ltEq"),
lt: wrapExprArg("lt"),
lessThan: wrapExprArg("lt"),
neq: wrapExprArg("neq"),
notEquals: wrapExprArg("neq"),
};
};
exports._Expr = _Expr;
const isScalarValue = (anyVal) => anyVal === null ||
anyVal === undefined ||
typeof anyVal === "number" ||
typeof anyVal === "bigint" ||
typeof anyVal === "string" ||
typeof anyVal === "boolean" ||
anyVal instanceof Date;
const isExpr = (anyVal) => {
try {
return anyVal?.[Symbol.toStringTag]?.() === "Expr";
}
catch (_err) {
return false;
}
};
const deserialize = (buf, format) => {
return (0, exports._Expr)(polars_internal_1.default.JsExpr.deserialize(buf, format));
};
exports.Expr = Object.assign(exports._Expr, {
isExpr,
deserialize,
});
const exprToLitOrExpr = (expr, stringToLit = true) => {
if ((0, types_1.isRegExp)(expr)) {
return (0, exports._Expr)(polars_internal_1.default.lit((0, utils_1.regexToString)(expr)));
}
if (typeof expr === "string" && !stringToLit) {
return (0, exports._Expr)(polars_internal_1.default.col(expr));
}
if (exports.Expr.isExpr(expr)) {
return expr;
}
if (series_1.Series.isSeries(expr)) {
return (0, exports._Expr)(polars_internal_1.default.litSeries(expr._s));
}
return (0, exports._Expr)(polars_internal_1.default.lit(expr));
};
exports.exprToLitOrExpr = exprToLitOrExpr;
/**
* Create an expression of type `Datetime` from its components.
*
* @param year Column or literal.
* @param month Column or literal, ranging from 1-12.
* @param day Column or literal, ranging from 1-31.
* @param hour Column or literal, ranging from 0-23.
* @param minute Column or literal, ranging from 0-59.
* @param second Column or literal, ranging from 0-59.
* @param microsecond Column or literal, ranging from 0-999999.
* @param options.timeUnit Time unit of the resulting expression.
* @param options.timeZone Time zone of the resulting expression.
* @param options.ambiguous How to handle ambiguous datetimes.
* @example
* ```
* > const df = pl.DataFrame({ month: [1, 2], day: [3, 4] });
* > df.select(pl.datetime(2024, pl.col("month"), pl.col("day")));
* shape: (2, 1)
* ┌────────────┐
* │ datetime │
* │ --- │
* │ datetime[μs] │
* ╞════════════╡
* │ 2024-01-03 │
* │ 2024-02-04 │
* └────────────┘
* ```
*/
function datetime(year, month, day, hour, minute, second, microsecond, options) {
const toExpr = (value) => (0, exports.exprToLitOrExpr)(value, false)._expr;
const isOptions = (value) => typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
!exports.Expr.isExpr(value) &&
!series_1.Series.isSeries(value);
let resolvedOptions = {};
const components = [];
for (const arg of [hour, minute, second, microsecond, options]) {
if (isOptions(arg)) {
resolvedOptions = arg;
}
else if (arg != null) {
components.push(arg);
}
}
const [hourValue, minuteValue, secondValue, microsecondValue] = components;
return (0, exports._Expr)(polars_internal_1.default.datetime(toExpr(year), toExpr(month), toExpr(day), hourValue == null ? undefined : toExpr(hourValue), minuteValue == null ? undefined : toExpr(minuteValue), secondValue == null ? undefined : toExpr(secondValue), microsecondValue == null ? undefined : toExpr(microsecondValue), resolvedOptions.timeUnit, resolvedOptions.timeZone, (0, exports.exprToLitOrExpr)(resolvedOptions.ambiguous ?? "raise", true)._expr));
}
/**
* Create an expression of type `Date` from its components.
*
* @param year Column or literal.
* @param month Column or literal, ranging from 1-12.
* @param day Column or literal, ranging from 1-31.
* @example
* ```
* > const df = pl.DataFrame({ month: [1, 2], day: [3, 4] });
* > df.select(pl.date(2024, pl.col("month"), pl.col("day")));
* shape: (2, 1)
* ┌────────────┐
* │ date │
* │ --- │
* │ date │
* ╞════════════╡
* │ 2024-01-03 │
* │ 2024-02-04 │
* └────────────┘
* ```
*/
function date(year, month, day) {
const toExpr = (value) => (0, exports.exprToLitOrExpr)(value, false)._expr;
return (0, exports._Expr)(polars_internal_1.default.date(toExpr(year), toExpr(month), toExpr(day)));
}
/**
* Create an expression of type `Duration` from distinct time components.
*
* @param options Duration components and optional time unit.
* @example
* ```
* > const df = pl.DataFrame({ add: [1, 2] });
* > df.select(pl.duration({ days: pl.col("add") }));
* shape: (2, 1)
* ┌──────────────┐
* │ duration │
* │ --- │
* │ duration[μs] │
* ╞══════════════╡
* │ 1d │
* │ 2d │
* └──────────────┘
* ```
*/
function duration(options = {}) {
const toExpr = (value) => value == null ? undefined : (0, exports.exprToLitOrExpr)(value, false)._expr;
return (0, exports._Expr)(polars_internal_1.default.duration(toExpr(options.weeks), toExpr(options.days), toExpr(options.hours), toExpr(options.minutes), toExpr(options.seconds), toExpr(options.milliseconds), toExpr(options.microseconds), toExpr(options.nanoseconds), options.timeUnit));
}