# pipe(f, g, ...)

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [function](/web/js/val/func.md) ⟩ [higher-order](/web/js/val/func/kind/higher.md) ⟩ example ⟩ pipe()

{% hint style="success" %}
function composition.

```javascript
pipe(f, g, h)(x) === h(g(f(x)))
compose(f, g, h)(x) === f(g(h(x)))
```

{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit ⟩ [pipe(f1, f2, ...)](https://replit.com/@pegasusroe/pipef1-f2#index.js)

```javascript
// ⭐ pipe:  
// - pipe(f1, f2, f3 ...)(x,y,z ...) =  ...f3(f2(f1(x,y,z ...)))
//        ╰── funcs ───╯ ╰──args──╯
function pipe(...funcs) {
    return function(...args) {
        return funcs.slice(1).reduce(
            (result, f) => f.call(this, result),  // r = ...f3(f2(r))
            funcs[0].apply(this, args)            // r = f1(x,y,z ...)
        );
    };
}

// ⭐ compose: 
// - compose(f, g, h)(x) = f(g(h(x))) = pipe(h, g, f)(x)
function compose(...funcs) {
    return pipe(...funcs.slice().reverse());
}
```

* example

```javascript
const sum = (x, y) => x + y;
const square = x => x * x;
const add3 = x => x + 3;

compose(square, sum)(2, 3)        // 25
pipe(sum, square)(2, 3)           // 25
pipe(sum, square, add3)(2, 3)     // 28
```

{% endtab %}

{% tab title="👥 相關" %}

* [Boolean](/web/js/val/prim/boolean.md)
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] [JavaScript: The Definitive Guide](/web/master/ref/javascript-the-definitive-guide.md) ⟩ 8.8.2 Higher-Order Functions ⭐️&#x20;
* [ ] Eloquent JavaScript ⟩ [higher-order functions](https://eloquentjavascript.net/05_higher_order.html#h_xxCc98lOBK)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/val/func/kind/higher/pipe.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
