Javascript's New Pipeline Operator Is Awesome!
By Jack Herrington
Share:
Key Concepts:
- Method Chaining
- Pipeline Operator (F#, Hack)
- Unary Function
- TC39 Proposal
- Temporary Arrays
- Expressions
- Topic (Hack Syntax)
1. Method Chaining and its Drawbacks:
- Method chaining involves sequentially applying methods to an object (e.g., array), like
.map().filter().sort(). - Example: Filtering an array of numbers to include only those >= 10, multiplying the results by 2, and summing them using
reduce. - Behind the scenes, method chaining creates temporary in-memory arrays (T1, T2, etc.) at each step, which can be inefficient.
2. F# Pipeline Operator Syntax:
- Syntax:
|>. - Requires unary functions at each step. A unary function takes a single input.
- Example:
numbers |> (x => x.filter(...)) |> (x => x.map(...)) |> (x => x.reduce(...)). - Advantage: Allows easy insertion of debugging steps (e.g.,
console.log) within the pipeline. - To insert
console.log, a unary function must still return the input (x) to maintain the pipeline's flow. - Example:
|> (x => { console.log(x); return x; }).
3. Setting up F# Syntax in Babel:
- Install the Quokka extension for dynamic evaluation.
- Configure Babel to use the
pipeline-operatorplugin. - Specify the F# proposal:
proposal: 'fsharp'.
4. Hack Pipeline Operator Syntax:
- Syntax:
|>. - Uses expressions instead of unary functions.
- Introduces the concept of a "topic," represented by a character (default:
%). - The topic refers to the input of the current expression (either the initial value or the output of the previous expression).
- Example:
numbers |> (% => %.filter(...)) |> (% => %.map(...)) |> (% => %.reduce(...)).
5. Debugging with Hack Syntax:
console.logwithin an expression disrupts the pipeline because it returnsundefined.- Solution: Use the comma operator to ensure the expression returns the topic.
- Example:
|> (% => (console.log(%), %))- Theconsole.logis executed, but the expression returns%. - Comma Operator: In an expression like
(A, B, C), the value of the entire expression isC.
6. TC39 Proposal Status and Conclusion:
- The pipeline operator proposal is currently in stage 2.
- Two competing syntaxes: F# and Hack.
- The F# version has faced multiple rejections.
- The video encourages viewers to express their preference for either syntax in the comments.
- The video offers the GitHub repository with the examples for free.
Chat with this Video
AI-PoweredHi! I can answer questions about this video "Javascript's New Pipeline Operator Is Awesome!". What would you like to know?
Chat is based on the transcript of this video and may not be 100% accurate.