Pipe-Funktion in JavaScript

Level 5388 Tastenanschläge

Pipe erstellt eine Funktionspipeline, die Daten durch mehrere Transformationen von links nach rechts verarbeitet.

JavaScript-Code

// Pipe-Funktion mit reduce (von links nach rechts)
// Anders als compose, das von rechts nach links arbeitet
1const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
2
// Individuelle Transformationsfunktionen definieren
3const trim = s => s.trim();
4const toLowerCase = s => s.toLowerCase();
// split zerlegt den String in ein Array von Wörtern
5const split = s => s.split(" ");
// join fügt die Wörter mit "-" wieder zusammen
6const join = arr => arr.join("-");
7
// Eine slugify-Funktion durch Verketten von Transformationen erstellen
// Datenfluss: trim -> toLowerCase -> split -> join
8const slugify = pipe(trim, toLowerCase, split, join);
9
// " Hello World " -> "hello-world"
10console.log(slugify(" Hello World "));
// "JavaScript Is Fun" -> "javascript-is-fun"
11console.log(slugify("JavaScript Is Fun"));
// " ONE TWO THREE " -> "one-two-three"
12console.log(slugify(" ONE TWO THREE "));

Ausgabe

hello-world
javascript-is-fun
one-two-three
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.

  • (× 16
  • )× 16
  • =× 13
  • .× 11
  • "× 10
  • ;× 9
  • >× 7
  • ,× 5
  • -× 1

Weitere JavaScript-Beispiele auf Level 5

← JavaScript-Tippübungen