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 -> f3
1const 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 <- f1
4const compose = (...fns) => (value) =>
5 fns.reduceRight((acc, fn) => fn(acc), value);
6
// Einfache Transformationsfunktionen
7const double = x => x * 2;
8const addTen = x => x + 10;
9const square = x => x * x;
10
// pipe: 5 -> double -> addTen -> square
// 5 -> 10 -> 20 -> 400
11const piped = pipe(double, addTen, square);
// compose(square, addTen, double) wendet zuerst double, dann addTen, dann square an
// Gleiches Ergebnis: 5 -> 10 -> 20 -> 400
12const composed = compose(square, addTen, double);
13
14console.log("Piped:", piped(5));
15console.log("Composed:", composed(5));
16
// Praktisches Beispiel: Namensverarbeitungs-Pipeline
17const processName = pipe(
// Entfernt Leerzeichen am Anfang und Ende
18 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
Diesen Code tippen üben

Ü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

Weitere JavaScript-Beispiele auf Level 5

← JavaScript-Tippübungen