반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- CloudFlare
- msw
- vue-cli
- svelte
- ts error
- vue3
- Testing
- caching
- ViTE
- api test
- import.meta.env
- rendering
- QUIC
- TLS
- https
- SSR
- vue
- devtools
- 비동기
- Cypress
- aws
- e2e
- csr
- custom command
- JavaScript
- web vital
- http3
- typeScript
- 선택자
- CSS
Archives
- Today
- Total
Develop Note by J.S.
[Javascript] Function Pipeline 본문
반응형
1. Function Pipeline
const addFive = (x) => x + 5;
const double = (x) => x * 2;
const minusOne = (x) => x - 1;
const result = minusOne(addFive(double(10)));
특정 값을 여러 함수에 순차적으로 전달하여 결과를 사용하는 코드는 가독성이 떨어집니다. Pipe를 정의하고 이를 사용해 코드 리팩토링 시 가독성이 좋아질 것입니다.
1) 코드 정의
// common.ts
export const _ = {
filter(predicate) {
return (array) => array.filter(predicate);
},
sort(compareFn) {
return (arr) => arr.sort(compareFn);
},
map(fn) {
return (arr) => arr.map(fn);
},
getLength(arr) {
return arr.length;
},
isLength(arr) {
return !!arr.length;
},
// ...등등 자주사용할 만한 function들?
};
export const commonPipe = (...funcs) => v => {
return funcs.reduce((res, func) => {
return func(res);
}, v);
};
2) 활용
[예시1]
const addFive = (x) => x + 5;
const double = (x) => x * 2;
const minusOne = (x) => x - 1;
// 기존코드
const result = minusOne(addFive(double(10)));
// Pipe코드
commonPipe(
double,
addFive,
minusOne
)(10);
[예시 2]
// 기존코드
list.filter((seat) => {
return Status.Ready === seat.status || Status.Seated === seat.status || Status.Empty === seat.status;
}).length;
// Pipe코드
const checkSeatStatus = (seat) => {
return (
Status.Ready === seat.status
|| Status.Seated === seat.status
|| Status.Empty === seat.status
);
};
commonPipe(
_.filter(checkSeatStatus),
_.getLength,
)(seatList);
2. Pipe Operator
파이프 연산자는 '|>' 기호를 사용하며 현재 ECMAScript 표준위원회에서 활발히 논의되고는 있지만, 표준에 포함될지 알 수 없는 단계입니다. 만약 나중에 pipe연산자가 생긴다면...
const result = minusOne(addFive(double(10)));
// pipe 연산자
const result = 10 |> double |> addFive |> minusOne;
위와 같이 사용될 수 있다고합니다만, 커뮤니티에서는 여러 사유로 반대되고 있다고 합니다.
반응형
'Language > Javascript' 카테고리의 다른 글
[Javascript] 컴파일 언어, 인터프리터 언어 (with. V8엔진, 웹 어셈블리) (0) | 2024.07.04 |
---|---|
[Javascript] Promise의 중단 처리 (AbortSignal) (0) | 2024.01.09 |
[Javascript] Event Loop, Task Queue (0) | 2023.09.18 |
[Javascript] Prototype (0) | 2023.06.29 |
[Javascript] This (0) | 2023.06.28 |