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 แล้วมันช่วงสวยงามเหลือเกิน 😆😆

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)