DEV Community

Cover image for Method Chaining In Javascript
Teerawit Laothong
Teerawit Laothong

Posted on

1

Method Chaining In Javascript

Javascript มันไม่มีการ Chain method call แบบสวย ๆ เหมือนภาษา functional programming อันอื่นบ้างหรอ(ว่ะ)?

ผมว่า dev หลาย ๆ คนที่เคยจับ javascript มาบ้างหรือใช้งานอยู่ทุกวัน ก็น่าจะเคยถามคำถามนี้ในใจกันอยู่หลายครั้ง ทั้งที่ลอง search ใน internet ก็มีอยู่หลายวิธี แต่มันก็ไม่มีวิธีดี ๆ ที่ถูกใจสักกะอย่าง

ผมเองก็เป็นหนึ่งในนั้นแหละ

แต่ ...........

เร็ว ๆ นี้เราจะสามารถใช้ไอ้เจ้าสิ่งนี้ได้แล้วผ่านตัว proposal ที่ชื่อว่า pipeline-operator รายละเอียดสามารถอ่านดูจากข้างใน proposal ได้เลยนะครับ ซึ่ง pipeline-operator ก็อยู่ใน stage 2 แล้วจากทั้งหมด 4 stage ด้วยกัน

ซึ่งบอกได้เลยว่าถ้าเสร็จเมื่อไหร code javascript เราจะสวยและอ่านง่ายขึ้นเยอะเลย หลาย ๆ คนที่เคยเกลียด javscript อาจจะเปลี่ยนใจก็ได้นะ (หรือป่าวนะ? 😋)

เราสามารถ test feature นี้ได้ผ่าน babel ดังนี้


// Create a New Directory for Your Project:
mkdir pipeline-operator-test
cd pipeline-operator-test

//  Initialize a New Node.js Project
npm init -y

//  Install Required Dependencies:
npm install \
    --save-dev \
    @babel/core 
    @babel/cli \
    @babel/preset-env \
    @babel/plugin-proposal-pipeline-operator
Enter fullscreen mode Exit fullscreen mode

สร้าง .babelrc file ขึ้นมาแล้ว copy, paste โล้ด..

{
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        [
            "@babel/plugin-proposal-pipeline-operator",
            {
                "proposal": "minimal"
            }
        ]
    ]
}
Enter fullscreen mode Exit fullscreen mode

ทีนี้เราก็สามารถ chain method call แบบนี้ได้แล้ว

const double = (n) => n * 2;
const increment = (n) => n + 1;

let result1 = 5
  |> double
  |> increment;

// หรือจะใช้แบบนี้ก็ได้
let result2 = 5
  |> double(%)
  |> increment(%);
Enter fullscreen mode Exit fullscreen mode

บ๊ะ .. เห็น code แล้วมันช่วงสวยงามเหลือเกิน 😆😆

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay