JavaScript API Reference
Complete API reference for Veloxx JavaScript/WebAssembly bindings.
Installation
Using npm
npm install veloxx-wasm
Using CDN
<script src="https://unpkg.com/veloxx-wasm/veloxx.js"></script>
Quick Start
import * as veloxx from 'veloxx-wasm';
// Initialize the WASM module
await veloxx.default();
// Create a DataFrame
const df = new veloxx.WasmDataFrame({
name: ["Alice", "Bob", "Charlie"],
age: [25, 30, 35],
salary: [50000.0, 75000.0, 60000.0]
});
// Basic operations
// Filter rows where age > 25 using an expression
const filtered = df.filter(veloxx.WasmExpr.greaterThan(veloxx.WasmExpr.column("age"), veloxx.WasmExpr.literal(new veloxx.WasmValue(25))));
// Select columns
const selected = df.selectColumns(["name", "salary"]);
console.log(`DataFrame has ${df.row_count} rows and ${df.column_count} columns`);
Core Classes
WasmDataFrame
The main data structure for working with tabular data in JavaScript.
Constructor
Creates a new DataFrame from an object where keys are column names and values are arrays of data.
Parameters:
columns: Object - Object mapping column names to data arrays
Example:
const df = new veloxx.WasmDataFrame({
name: ["Alice", "Bob", "Charlie"],
age: [25, 30, 35],
active: [true, false, true],
salary: [50000.0, 75000.0, 60000.0]
});
Properties
Returns the number of rows in the DataFrame.
Example:
console.log(`DataFrame has ${df.row_count} rows`);
Returns the number of columns in the DataFrame.
Example:
console.log(`DataFrame has ${df.column_count} columns`);
Methods
Returns an array of column names.
Example:
const names = df.columnNames();
names.forEach(name => console.log(`Column: ${name}`));
Gets a column by name.
Parameters:
name: string - Name of the column to retrieve
Example:
const ageColumn = df.getColumn("age");
if (ageColumn) {
console.log(`Age column has ${ageColumn.len} values`);
}
Data Manipulation
Filters rows based on a boolean expression.
Parameters:
expression: WasmExpr - A boolean expression to filter rows
Example:
// Filter rows where age > 25
const filtered = df.filter(veloxx.WasmExpr.greaterThan(
veloxx.WasmExpr.column("age"),
veloxx.WasmExpr.literal(new veloxx.WasmValue(25))
));
Selects specific columns from the DataFrame.
Parameters:
names: string[] - Names of columns to select
Example:
const selected = df.selectColumns(["name", "age"]);
Removes specified columns from the DataFrame.
Parameters:
names: string[] - Names of columns to drop
Example:
const withoutId = df.dropColumns(["id"]);
Renames a column in the DataFrame.
Parameters:
oldName: string - Current name of the column
newName: string - New name for the column
Example:
const renamed = df.renameColumn("age", "years");
Adds a new column or replaces an existing one using an expression.
Parameters:
name: string - Name of the new column
expr: WasmExpr - Expression to compute the column values
Example:
// Add a column with salary + 1000 bonus
const salaryCol = veloxx.WasmExpr.column("salary");
const bonus = veloxx.WasmExpr.literal(new veloxx.WasmValue(1000.0));
const expr = veloxx.WasmExpr.add(salaryCol, bonus);
const withBonus = df.withColumn("salary_with_bonus", expr);
Grouping and Aggregation
Groups the DataFrame by specified columns.
Parameters:
byColumns: string[] - Columns to group by
Example:
const grouped = df.groupBy(["department"]);
const result = grouped.agg([["salary", "mean"], ["age", "count"]]);
Generates descriptive statistics for numeric columns.
Example:
const stats = df.describe();
console.log(stats);
Statistical Methods
Calculates the Pearson correlation between two numeric columns.
Parameters:
col1Name: string - Name of the first column
col2Name: string - Name of the second column
Example:
const corr = df.correlation("age", "salary");
console.log(`Age-Salary correlation: ${corr.toFixed(3)}`);
Calculates the covariance between two numeric columns.
Parameters:
col1Name: string - Name of the first column
col2Name: string - Name of the second column
Example:
const cov = df.covariance("age", "salary");
console.log(`Age-Salary covariance: ${cov.toFixed(2)}`);
Data Cleaning
Removes rows containing any null values. If subset
is provided, only nulls in those columns are considered.
Parameters:
subset: string[] - Optional: List of column names to consider for dropping nulls. If omitted, all columns are considered.
Example:
const cleanDf = df.dropNulls();
// Drop rows with nulls only in 'age' or 'salary'
const cleanDfSubset = df.dropNulls(['age', 'salary']);
Fills null values with a specified value. The filling only occurs if the value
's type matches the DataType
of the column being processed. If subset
is provided, only nulls in those columns are filled.
Parameters:
value: WasmValue - Value to use for filling nulls
subset: string[] - Optional: List of column names to consider for filling nulls. If omitted, all columns are considered.
Example:
const filled = df.fillNulls(new veloxx.WasmValue(0)); // Fill numeric nulls with 0 in all columns
const filledStr = df.fillNulls(new veloxx.WasmValue("Unknown"), ["category"]); // Fill string nulls in 'category' column
Concatenation
Appends another DataFrame vertically.
Parameters:
other: WasmDataFrame - DataFrame to append
Example:
const combined = df1.append(df2);
WasmSeries
Represents a single column of data with a specific type.
Constructor
Creates a new Series with automatic type inference.
Parameters:
name: string - Name of the series
data: any[] - Array of values
Example:
const ages = new veloxx.WasmSeries("age", [25, 30, null, 35]);
const names = new veloxx.WasmSeries("name", ["Alice", "Bob", "Charlie"]);
const active = new veloxx.WasmSeries("active", [true, false, true]);
Properties
Returns the name of the Series.
Example:
console.log(`Series name: ${series.name}`);
Returns the length of the Series.
Example:
console.log(`Series has ${series.len} values`);
Returns true if the Series is empty.
Example:
if (series.isEmpty) {
console.log("Series is empty");
}
Returns the data type of the Series.
Example:
console.log(`Data type: ${series.dataType}`);
Methods
Gets the value at the specified index.
Parameters:
index: number - Index position
Example:
const value = series.getValue(0);
console.log(`First value: ${value}`);
Sets a new name for the Series.
Parameters:
newName: string - New name for the series
Example:
series.setName("new_column_name");
Filters the Series by index positions.
Parameters:
rowIndices: number[] - Array of indices to keep
Example:
const filtered = series.filter([0, 2, 4]);
Casts the Series to a different data type.
Parameters:
toType: WasmDataType - Target data type
Example:
const asFloat = series.cast(veloxx.WasmDataType.F64);
Appends another Series to this one.
Parameters:
other: WasmSeries - Series to append
Example:
const combined = series1.append(series2);
Statistical Methods
Returns the count of non-null values.
Example:
const nonNullCount = series.count();
Returns the minimum value in the Series.
Example:
const minValue = series.min();
console.log(`Minimum: ${minValue}`);
Returns the maximum value in the Series.
Example:
const maxValue = series.max();
console.log(`Maximum: ${maxValue}`);
Returns the median value for numeric Series.
Example:
const medianValue = series.median();
console.log(`Median: ${medianValue}`);
Returns the standard deviation for numeric Series.
Example:
const stdDev = series.stdDev();
console.log(`Standard Deviation: ${stdDev}`);
Calculates the Pearson correlation between two numeric Series.
Parameters:
other: WasmSeries - Other series to correlate with
Example:
const corr = ageSeries.correlation(salarySeries);
console.log(`Correlation: ${corr}`);
Calculates the covariance between two numeric Series.
Parameters:
other: WasmSeries - Other series to calculate covariance with
Example:
const cov = ageSeries.covariance(salarySeries);
console.log(`Covariance: ${cov}`);
Interpolates null values using linear interpolation for numeric Series.
Example:
const s = new veloxx.WasmSeries("data", [1, null, 3, null, 5]);
const interpolatedS = s.interpolateNulls();
console.log(`Interpolated: ${interpolatedS.toArray()}`);
Appends another Series to this one.
Parameters:
other: WasmSeries - Series to append
Example:
const s1 = new veloxx.WasmSeries("data", [1, 2]);
const s2 = new veloxx.WasmSeries("data", [3, 4]);
const combined = s1.append(s2);
console.log(`Combined: ${combined.toArray()}`);
WasmGroupedDataFrame
Represents a grouped DataFrame for aggregation operations.
Methods
Performs aggregation operations on grouped data.
Parameters:
aggregations: [string, string][] - Array of [column, operation] pairs
Available operations: "sum"
, "mean"
, "count"
, "min"
, "max"
, "std"
Example:
const grouped = df.groupBy(["department"]);
const result = grouped.agg([
["salary", "mean"],
["age", "count"],
["bonus", "sum"]
]);
WasmExpr
Represents expressions for creating computed columns.
Static Methods
Creates an expression that references a column.
Parameters:
name: string - Column name
Example:
const ageExpr = veloxx.WasmExpr.column("age");
Creates an expression with a literal value.
Parameters:
value: WasmValue - Literal value
Example:
const literalExpr = veloxx.WasmExpr.literal(new veloxx.WasmValue(100));
Arithmetic Operations
Creates an addition expression.
Example:
const sum = veloxx.WasmExpr.add(
veloxx.WasmExpr.column("salary"),
veloxx.WasmExpr.literal(new veloxx.WasmValue(1000))
);
Creates a subtraction expression.
Example:
const diff = veloxx.WasmExpr.subtract(
veloxx.WasmExpr.column("revenue"),
veloxx.WasmExpr.column("cost")
);
Creates a multiplication expression.
Example:
const product = veloxx.WasmExpr.multiply(
veloxx.WasmExpr.column("price"),
veloxx.WasmExpr.column("quantity")
);
Creates a division expression.
Example:
const ratio = veloxx.WasmExpr.divide(
veloxx.WasmExpr.column("profit"),
veloxx.WasmExpr.column("revenue")
);
Comparison Operations
Creates an equality comparison expression.
Example:
const isActive = veloxx.WasmExpr.equals(
veloxx.WasmExpr.column("status"),
veloxx.WasmExpr.literal(new veloxx.WasmValue("active"))
);
Creates a not-equals comparison expression.
Creates a greater-than comparison expression.
Creates a less-than comparison expression.
Creates a greater-than-or-equal comparison expression.
Creates a less-than-or-equal comparison expression.
Logical Operations
Creates a logical AND expression.
Example:
const condition = veloxx.WasmExpr.and(
veloxx.WasmExpr.greaterThan(
veloxx.WasmExpr.column("age"),
veloxx.WasmExpr.literal(new veloxx.WasmValue(25))
),
veloxx.WasmExpr.equals(
veloxx.WasmExpr.column("department"),
veloxx.WasmExpr.literal(new veloxx.WasmValue("Engineering"))
)
);
Creates a logical OR expression.
Creates a logical NOT expression.
Parameters:
expr: WasmExpr - Expression to negate
WasmValue
Represents a typed value that can be used in expressions and operations.
Constructor
Creates a new WasmValue with automatic type inference.
Parameters:
value: any - JavaScript value (number, string, boolean, null)
Example:
const intValue = new veloxx.WasmValue(42);
const floatValue = new veloxx.WasmValue(3.14);
const stringValue = new veloxx.WasmValue("hello");
const boolValue = new veloxx.WasmValue(true);
const nullValue = new veloxx.WasmValue(null);
Methods
Converts the WasmValue back to a JavaScript value.
Example:
const wasmVal = new veloxx.WasmValue(42);
const jsVal = wasmVal.toJsValue(); // Returns 42
WasmDataType
Enumeration of supported data types.
Values
WasmDataType.I32
- 32-bit signed integerWasmDataType.F64
- 64-bit floating pointWasmDataType.Bool
- BooleanWasmDataType.String
- StringWasmDataType.DateTime
- DateTime (stored as timestamp)
Example:
// Check data type
if (series.dataType === veloxx.WasmDataType.F64) {
console.log("This is a numeric series");
}
// Cast to different type
const asString = series.cast(veloxx.WasmDataType.String);
Advanced Examples
Complex Data Processing Pipeline
import * as veloxx from 'veloxx-wasm';
// Initialize WASM
await veloxx.default();
// Create sample data
const df = new veloxx.WasmDataFrame({
employee_id: [1, 2, 3, 4, 5],
name: ["Alice", "Bob", "Charlie", "Diana", "Eve"],
department: ["Engineering", "Sales", "Engineering", "HR", "Sales"],
salary: [75000, 65000, 80000, 60000, 70000],
years_experience: [5, 3, 7, 2, 4],
performance_score: [4.2, 3.8, 4.5, 3.9, 4.1]
});
// Calculate salary per year of experience
const salaryPerYear = veloxx.WasmExpr.divide(
veloxx.WasmExpr.column("salary"),
veloxx.WasmExpr.column("years_experience")
);
const enriched = df.withColumn("salary_per_year", salaryPerYear);
// Filter high performers (score > 4.0)
const highPerformers = enriched.filter(
veloxx.WasmExpr.greaterThan(
veloxx.WasmExpr.column("performance_score"),
veloxx.WasmExpr.literal(new veloxx.WasmValue(4.0))
)
);
// Group by department and calculate statistics
const departmentStats = highPerformers
.groupBy(["department"])
.agg([
["salary", "mean"],
["years_experience", "mean"],
["performance_score", "mean"]
]);
console.log(`High performer statistics by department:`);
console.log(departmentStats);
Working with Missing Data
// Create DataFrame with null values
const dfWithNulls = new veloxx.WasmDataFrame({
id: [1, 2, 3, 4, 5],
value: [10.5, null, 15.2, null, 20.1],
category: ["A", "B", null, "A", "B"]
});
// Option 1: Drop rows with any null values
const cleanDf = dfWithNulls.dropNulls();
console.log("\nDataFrame after dropping nulls:");
console.log(cleanDf);
// Option 2: Fill nulls with specific values
// Fill numeric nulls with 0
const filledNumeric = dfWithNulls.fillNulls(new veloxx.WasmValue(0));
console.log("\nDataFrame after filling numeric nulls with 0:");
console.log(filledNumeric);
// Fill string nulls with "Unknown" in the 'category' column
const filledString = dfWithNulls.fillNulls(new veloxx.WasmValue("Unknown"), ["category"]);
console.log("\nDataFrame after filling string nulls with \"Unknown\":");
console.log(filledString);
Statistical Analysis
// Create sample dataset
const salesData = new veloxx.WasmDataFrame({
month: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
revenue: [100000, 120000, 95000, 130000, 140000, 125000],
costs: [60000, 70000, 55000, 75000, 80000, 70000],
customers: [1000, 1200, 950, 1300, 1400, 1250]
});
// Calculate profit
const profit = veloxx.WasmExpr.subtract(
veloxx.WasmExpr.column("revenue"),
veloxx.WasmExpr.column("costs")
);
const withProfit = salesData.withColumn("profit", profit);
// Calculate correlations
const revenueSeries = withProfit.getColumn("revenue");
const customerSeries = withProfit.getColumn("customers");
const profitSeries = withProfit.getColumn("profit");
const revenueCustomerCorr = revenueSeries.correlation(customerSeries);
const profitRevenueCorr = profitSeries.correlation(revenueSeries);
console.log(`Revenue-Customer correlation: ${revenueCustomerCorr.toFixed(3)}`);
console.log(`Profit-Revenue correlation: ${profitRevenueCorr.toFixed(3)}`);
// Generate descriptive statistics
const stats = withProfit.describe();
console.log("Descriptive Statistics:");
console.log(stats);
Error Handling
Veloxx WebAssembly methods can throw exceptions for invalid operations or data. It's crucial to handle these errors using try-catch
blocks.
import * as veloxx from 'veloxx-wasm';
async function runWithErrorHandling() {
await veloxx.default(); // Initialize WASM
try {
// Example 1: Invalid DataFrame creation (mixed types in a column)
const dfInvalid = new veloxx.WasmDataFrame({
data: [1, "string", 3] // This will throw an error
});
console.log(dfInvalid); // This line won't be reached
} catch (error) {
console.error("Error creating DataFrame:", error.message);
}
try {
const df = new veloxx.WasmDataFrame({
id: [1, 2, 3],
value: [10, 20, 30]
});
// Example 2: Accessing a non-existent column
const nonExistentColumn = df.getColumn("nonexistent");
if (nonExistentColumn) {
console.log(nonExistentColumn.toArray());
}
} catch (error) {
console.error("Error accessing column:", error.message);
}
try {
const df = new veloxx.WasmDataFrame({
a: [1, 2],
b: [3, 4]
});
// Example 3: Performing an operation on incompatible types
const invalidExpr = veloxx.WasmExpr.add(
veloxx.WasmExpr.column("a"),
veloxx.WasmExpr.literal(new veloxx.WasmValue("text"))
);
const result = df.withColumn("new_col", invalidExpr);
console.log(result);
} catch (error) {
console.error("Error with expression:", error.message);
}
}
runWithErrorHandling();
Performance Tips
To maximize performance when using Veloxx WebAssembly bindings, consider the following best practices:
-
Minimize Data Transfers: Transferring data between JavaScript and WebAssembly can incur overhead. Perform as many operations as possible within the WebAssembly context before transferring results back to JavaScript.
-
Chain Operations: Veloxx operations are optimized when chained together. This allows the underlying Rust engine to apply optimizations like lazy evaluation and query plan optimization.
// Good: Chained operations
const result = df
.filter(veloxx.WasmExpr.greaterThan(veloxx.WasmExpr.column("age"), veloxx.WasmExpr.literal(new veloxx.WasmValue(18))))
.selectColumns(["name", "salary"])
.groupBy(["department"])
.agg([["salary", "mean"]]); -
Use Expressions for Complex Logic: For column-wise computations and complex filtering, leverage
WasmExpr
instead of native JavaScript loops.WasmExpr
operations are executed efficiently in WebAssembly.// Good: Using WasmExpr for calculations
const totalCompExpr = veloxx.WasmExpr.add(
veloxx.WasmExpr.column("base_salary"),
veloxx.WasmExpr.column("bonus")
);
const dfWithTotalComp = df.withColumn("total_compensation", totalCompExpr);
// Bad: Performing calculations in JavaScript loop
// const salaries = df.getColumn("salary").toArray();
// const bonuses = df.getColumn("bonus").toArray();
// const totalComps = salaries.map((s, i) => s + bonuses[i]);
// This involves data transfer and less optimized computation. -
Filter Early: Apply filtering operations as early as possible in your data processing pipeline to reduce the amount of data processed by subsequent, more expensive operations.
-
Reuse
WasmValue
andWasmExpr
Objects: For frequently used literal values or expressions, create them once and reuse them to avoid redundant object creation.// Good: Reusing WasmValue and WasmExpr
const threshold = new veloxx.WasmValue(1000);
const salesColumn = veloxx.WasmExpr.column("sales");
const highSalesFilter = veloxx.WasmExpr.greaterThan(salesColumn, veloxx.WasmExpr.literal(threshold));
const filteredDf1 = df.filter(highSalesFilter);
const filteredDf2 = anotherDf.filter(highSalesFilter);
Browser Compatibility
Veloxx WebAssembly bindings are compatible with:
- Chrome/Edge: 57+
- Firefox: 52+
- Safari: 11+
- Node.js: 12+
For older browsers, consider using a WebAssembly polyfill.
TypeScript Support
Type definitions are included with the package:
import * as veloxx from 'veloxx-wasm';
interface EmployeeData {
name: string[];
age: number[];
salary: number[];
}
const data: EmployeeData = {
name: ["Alice", "Bob"],
age: [30, 25],
salary: [75000, 65000]
};
const df: veloxx.WasmDataFrame = new veloxx.WasmDataFrame(data);