-1

Reading the pipeline proposal in javascript I found this snippet:

value.one().two().three()

And I wondered if there's a way to implement something like this.

Let's say it should work like this:

one().two().three() // "1-2-3"

two().one().three() // "2-1-3"

two().two().two().one() // "2-2-2-1"

The only thing close to this I was able to implement was this:

const one = () => ({ two: () => ({ three: () => "1-2-3" }) });

one().two().three() // 1-2-3

But this is obviously not a flexible solution to the problem.

cubefox
  • 1,251
  • 14
  • 29
  • 1
    Not the downvoter here but you're missing the point of the pipe operator. What you ask about is so called "fluent interface" (or chained interface) and is [perfectly doable at the moment](https://stackoverflow.com/questions/31966627/javascript-how-to-fluent-api-also-calling-chaining) – Wiktor Zychla Sep 25 '22 at 08:26
  • 1
    @WiktorZychla Yeah, thanks. Found an answer thanks to the term "fluent interface". – cubefox Sep 25 '22 at 08:33

1 Answers1

0

Apparently this is called a "Fluent Interface" and it can be implemented like this


function Num() {
  this.string = ''
  this.one = () => {
    this.string += '-1';
    return this;
  }
  this.two = () => {
    this.string += '-2';
    return this;
  }
  this.three = () => {
    this.string += '-3';
    return this;
  }
  this.value = () => {
    return this.string.substring(1);
  }
}

const num = new Num()


console.log(num.one().two().two().two().three().value())
cubefox
  • 1,251
  • 14
  • 29