Pipeline-Komposition in JavaScript
Level 5604 Tastenanschläge
Dies implementiert pipe und compose für Funktionskompositionsmuster.
JavaScript-Code
// pipe: Funktionskomposition von links nach rechts// Der Wert fließt durch Funktionen in Reihenfolge: f1 -> f2 -> f31const pipe = (...fns) => (value) =>2 fns.reduce((acc, fn) => fn(acc), value);3 // compose: Funktionskomposition von rechts nach links (traditionell)// Der Wert fließt durch Funktionen in umgekehrter Reihenfolge: f3 <- f2 <- f14const compose = (...fns) => (value) =>5 fns.reduceRight((acc, fn) => fn(acc), value);6 // Einfache Transformationsfunktionen7const double = x => x * 2;8const addTen = x => x + 10;9const square = x => x * x;10 // pipe: 5 -> double -> addTen -> square// 5 -> 10 -> 20 -> 40011const piped = pipe(double, addTen, square);// compose(square, addTen, double) wendet zuerst double, dann addTen, dann square an// Gleiches Ergebnis: 5 -> 10 -> 20 -> 40012const composed = compose(square, addTen, double);13 14console.log("Piped:", piped(5));15console.log("Composed:", composed(5));16 // Praktisches Beispiel: Namensverarbeitungs-Pipeline17const processName = pipe( // Entfernt Leerzeichen am Anfang und Ende18 str => str.trim(), // Wandelt alles in Kleinbuchstaben um: "john doe"19 str => str.toLowerCase(), // Schreibt den ersten Buchstaben jedes Worts groß: "John Doe"20 str => str.split(" ").map(w => w[0].toUpperCase() + w.slice(1)).join(" ")21);22console.log(processName(" john DOE "));Ausgabe
Piped: 400 Composed: 400 John Doe
Übe, diesen Code zu tippen. Ergebnisse werden nicht in der Rangliste gespeichert.
Symbole in diesem Code
Die Symbole, die du in diesem JavaScript-Code tippst, und wie oft sie vorkommen.
(× 26)× 26=× 21.× 18>× 13,× 12;× 11"× 10:× 2*× 2