|
| 1 | +/** |
| 2 | + * Filtering method: expr$ |
| 3 | + * |
| 4 | + * This file provides the expr$ method for DataFrame rows using template literals |
| 5 | + * This provides a more intuitive syntax for filtering |
| 6 | + * |
| 7 | + * @module methods/dataframe/filtering/expr$ |
| 8 | + */ |
| 9 | + |
| 10 | +import { createTypedSeries } from '../../../data/utils/createTypedArray.js'; |
| 11 | + |
| 12 | +/** |
| 13 | + * Filters rows in a DataFrame using a template literal expression. |
| 14 | + * This provides a more intuitive syntax for filtering. |
| 15 | + * |
| 16 | + * @param {Object} df - DataFrame instance |
| 17 | + * @param {TemplateStringsArray} strings - Template strings array |
| 18 | + * @param {...any} values - Values to interpolate into the template |
| 19 | + * @returns {Object} - New DataFrame with filtered rows |
| 20 | + * |
| 21 | + * @example |
| 22 | + * // Filter rows where age > 30 and city includes "York" |
| 23 | + * df.expr$`age > 30 && city_includes("York")` |
| 24 | + */ |
| 25 | +export function expr$(df, strings, ...values) { |
| 26 | + // Create an expression from the template string |
| 27 | + const expression = String.raw({ raw: strings }, ...values); |
| 28 | + |
| 29 | + // Transform the expression, replacing string methods with special functions |
| 30 | + const processedExpr = expression |
| 31 | + .replace(/([a-zA-Z0-9_]+)_includes\(([^)]+)\)/g, '$1.includes($2)') |
| 32 | + .replace(/([a-zA-Z0-9_]+)_startsWith\(([^)]+)\)/g, '$1.startsWith($2)') |
| 33 | + .replace(/([a-zA-Z0-9_]+)_endsWith\(([^)]+)\)/g, '$1.endsWith($2)') |
| 34 | + .replace(/([a-zA-Z0-9_]+)_match\(([^)]+)\)/g, '$1.match($2)'); |
| 35 | + |
| 36 | + // Create a predicate function for filtering rows |
| 37 | + const predicate = createPredicate(processedExpr); |
| 38 | + |
| 39 | + // Get DataFrame rows |
| 40 | + const rows = df.toArray(); |
| 41 | + const allColumns = df.columns; |
| 42 | + |
| 43 | + // Filter rows by predicate |
| 44 | + const filteredRows = rows.filter((row) => predicate(row)); |
| 45 | + |
| 46 | + // If no matching rows, return an empty DataFrame with the same columns and column types |
| 47 | + if (filteredRows.length === 0) { |
| 48 | + // Create a new DataFrame instance with the same options as the original |
| 49 | + const result = new df.constructor({}, df._options); |
| 50 | + |
| 51 | + // For each column, create a Series with the appropriate type |
| 52 | + for (const col of allColumns) { |
| 53 | + // Get the original column data to determine its type |
| 54 | + const originalColumn = df._columns[col]; |
| 55 | + const originalArray = originalColumn.vector.__data; |
| 56 | + |
| 57 | + // Create an empty array with the same type |
| 58 | + if (ArrayBuffer.isView(originalArray) && !(originalArray instanceof DataView)) { |
| 59 | + const TypedArrayConstructor = originalArray.constructor; |
| 60 | + const emptyTypedArray = new TypedArrayConstructor(0); |
| 61 | + result._columns[col] = createTypedSeries(emptyTypedArray, col, df); |
| 62 | + } else { |
| 63 | + result._columns[col] = createTypedSeries([], col, df); |
| 64 | + } |
| 65 | + |
| 66 | + // Add to column order |
| 67 | + if (!result._order.includes(col)) { |
| 68 | + result._order.push(col); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return result; |
| 73 | + } |
| 74 | + |
| 75 | + // For non-empty results, create a new DataFrame with filtered rows |
| 76 | + // Create a new DataFrame instance with the same options as the original |
| 77 | + const result = new df.constructor({}, df._options); |
| 78 | + |
| 79 | + // For each column, create a Series with the appropriate type |
| 80 | + for (const col of allColumns) { |
| 81 | + // Get the original column data to determine its type |
| 82 | + const originalColumn = df._columns[col]; |
| 83 | + const originalArray = originalColumn.vector.__data; |
| 84 | + |
| 85 | + // Extract values for this column from the filtered rows |
| 86 | + const values = filteredRows.map(row => row[col]); |
| 87 | + |
| 88 | + // Preserve the array type if it's a typed array |
| 89 | + if (ArrayBuffer.isView(originalArray) && !(originalArray instanceof DataView)) { |
| 90 | + const TypedArrayConstructor = originalArray.constructor; |
| 91 | + const typedValues = new TypedArrayConstructor(values.length); |
| 92 | + values.forEach((value, i) => { |
| 93 | + typedValues[i] = value; |
| 94 | + }); |
| 95 | + result._columns[col] = createTypedSeries(typedValues, col, df); |
| 96 | + } else { |
| 97 | + result._columns[col] = createTypedSeries(values, col, df); |
| 98 | + } |
| 99 | + |
| 100 | + // Add to column order |
| 101 | + if (!result._order.includes(col)) { |
| 102 | + result._order.push(col); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + return result; |
| 107 | +} |
| 108 | + |
| 109 | +/** |
| 110 | + * Create a predicate function for filtering rows |
| 111 | + * |
| 112 | + * @param {string} expr - Expression to evaluate |
| 113 | + * @returns {Function} - Predicate function |
| 114 | + * @private |
| 115 | + */ |
| 116 | +function createPredicate(expr) { |
| 117 | + try { |
| 118 | + // Use Function instead of eval for better security |
| 119 | + return new Function( |
| 120 | + 'row', |
| 121 | + ` |
| 122 | + try { |
| 123 | + with (row) { |
| 124 | + return ${expr}; |
| 125 | + } |
| 126 | + } catch (e) { |
| 127 | + return false; |
| 128 | + } |
| 129 | + `, |
| 130 | + ); |
| 131 | + } catch (e) { |
| 132 | + throw new Error(`Invalid expression: ${expr}. Error: ${e.message}`); |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +// Export the expr$ method directly |
| 137 | +export { expr$ }; |
0 commit comments