|
| 1 | +# Chute |
| 2 | +A vanilla JavaScript function for pipeline style chaining methods AND functions. |
| 3 | + |
| 4 | +- V 2024-11-27: |
| 5 | + - 3KB with comments |
| 6 | + - < 1KB minified |
| 7 | + |
| 8 | +## How to |
| 9 | +- Add the function to your project |
| 10 | +- Call via `chute(initial_data)` |
| 11 | + |
| 12 | +```js |
| 13 | +let initial_data = [1, 2, 4] |
| 14 | +const result = chute(initial_data,/*any functions…*/push(8)) |
| 15 | + //swap between function calls and method calls as needed. |
| 16 | + //call any method native to the current data as normal: |
| 17 | + .map(double) |
| 18 | + //`.log` calls a built in method that takes 0+ arguments. |
| 19 | + .log('doubled:') |
| 20 | + //`.log` logs any arguments and the data, then resumes. |
| 21 | + .filter(greater_than(4)) |
| 22 | + //`.and` calls a built in method that takes 1+ functions. |
| 23 | + //`.and(f1,f2)` sends data to f1, then f1's return to f2. |
| 24 | + .and(push(32),push(64)) |
| 25 | + //nameless calls work the same way as `.and`: |
| 26 | + (push(80,128),push(256)) |
| 27 | + //each sub-chain uses a reducer and mimics nested calls. |
| 28 | + //one call `(f1,f2)` == `f2(f1(data))` |
| 29 | + //many calls `(f1)(f2)` == `data=f1(data);data=f2(data)` |
| 30 | + ('reverse')//strings call methods that need no arguments. |
| 31 | + //this allows unbroken sequences: `(f1,'method',f2)` |
| 32 | + //'.tap' calls a built in method that takes a function. |
| 33 | + //'.tap(f1)' sends data to f1 but ignores the result. |
| 34 | + .log('pre-tap') |
| 35 | + .tap(mutate)//.tap functions might mutate data directly. |
| 36 | + .log('post-tap') |
| 37 | + .reduce(add_up) |
| 38 | + //'.if' calls an inbuilt method that takes 2 arguments. |
| 39 | + .if( |
| 40 | + //a boolean |
| 41 | + //or a function that tests data and return a boolean. |
| 42 | + greater_than(64), |
| 43 | + //a function to send data to if the condition === true. |
| 44 | + halve |
| 45 | + ) |
| 46 | + .toString() |
| 47 | + (append('.')) |
| 48 | + ()//an empty call returns the final value |
| 49 | + //from this point, method calls directly act on the data. |
| 50 | + .replace('.','!') |
| 51 | + |
| 52 | +log({result}) |
| 53 | +//Demo Helper Functions |
| 54 | +function push (...a){return l => (l.push(...a),l)} |
| 55 | +function log (x){console.log('outer_log',x);return x} |
| 56 | +function greater_than(n){ return x => x > n} |
| 57 | +function double(x){return x * 2} |
| 58 | +function halve(x){return x / 2} |
| 59 | +function add_up(a, b){return a + b} |
| 60 | +function append(x){return d => d+x} |
| 61 | +function mutate (data){ |
| 62 | + data.length=0 |
| 63 | + data.push(1452,1386,1483,1475) |
| 64 | + return 'chucks this returned value' |
| 65 | +} |
| 66 | +``` |
0 commit comments