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
const filtered = df.filter([0, 2]); // Filter rows by indices
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 by index positions.
Parameters:
rowIndices: number[] - Array of row indices to keep
Example:
// Keep only rows 0 and 2
const filtered = df.filter([0, 2]);
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.
Example:
const cleanDf = df.dropNulls();
Fills null values with a specified value.
Parameters:
value: WasmValue - Value to use for filling nulls
Example:
const filled = df.fillNulls(new veloxx.WasmValue(0)); // Fill with 0
const filledStr = df.fillNulls(new veloxx.WasmValue("Unknown")); // Fill with string
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 correlation with another numeric Series.
Parameters:
other: WasmSeries - Other series to correlate with
Example:
const corr = ageSeries.correlation(salarySeries);
console.log(`Correlation: ${corr}`);
Calculates the covariance with another numeric Series.
Parameters:
other: WasmSeries - Other series to calculate covariance with
Example:
const cov = ageSeries.covariance(salarySeries);
console.log(`Covariance: ${cov}`);
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(
enriched.getColumn("performance_score")
.filter([0, 2, 4]) // Indices where score > 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();
// Option 2: Fill nulls with specific values
const filledDf = dfWithNulls
.fillNulls(new veloxx.WasmValue(0)) // Fill numeric nulls with 0
.fillNulls(new veloxx.WasmValue("Unknown")); // Fill string nulls
// Option 3: Fill nulls per column type
const valueFilled = dfWithNulls.fillNulls(new veloxx.WasmValue(-1));
const categoryFilled = valueFilled.fillNulls(new veloxx.WasmValue("Missing"));
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 revenueCustomerCorr = withProfit.correlation("revenue", "customers");
const profitRevenueCorr = withProfit.correlation("profit", "revenue");
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
All methods that can fail return JavaScript promises or throw exceptions. Always wrap operations in try-catch blocks:
try {
const df = new veloxx.WasmDataFrame({
invalid_data: [1, "string", true] // Mixed types
});
const result = df.selectColumns(["nonexistent_column"]);
} catch (error) {
console.error("Operation failed:", error.message);
}
Performance Tips
- Batch Operations: Combine multiple operations into a single chain when possible
- Avoid Frequent Type Conversions: Keep data in consistent types
- Use Appropriate Data Types: Choose the most specific type for your data
- Filter Early: Apply filters before expensive operations like grouping
- Reuse Expressions: Store complex expressions in variables for reuse
// Good: Chain operations
const result = df
.filter([0, 1, 2])
.selectColumns(["name", "salary"])
.groupBy(["department"])
.agg([["salary", "mean"]]);
// Good: Reuse expressions
const salaryExpr = veloxx.WasmExpr.column("salary");
const bonusExpr = veloxx.WasmExpr.literal(new veloxx.WasmValue(1000));
const totalComp = veloxx.WasmExpr.add(salaryExpr, bonusExpr);
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);