본문으로 바로가기
728x90

reduce

reduce는 사용자가 제공한 콜백 함수를 순서대로 실행하여 이전 요소에 대한 계산의 반환 값을 전달하여, 최종 결과로 단일 값을 제공합니다.

const numbers = [1, 2, 3, 4, 5];

// Summing up all the numbers from left to right
const sumLeft = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, '');

console.log(sumLeft); // Output: '12345'

또한 functional programming으로 코드를 작성한다면 reduce를 이용해서 pipe를 아주 쉽게 만들 수 있습니다.

const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x)

const double = (x) => x * 2
const add1 = (x) => x + 1

pipe(double, add1)(100) // 201

 

reduceRight은 언제 사용할까요?

크게 다르지 않습니다. 단지 값에 대해 오른쪽에서 왼쪽으로 읽는 차이입니다.

const numbers = [1, 2, 3, 4, 5];

// Concatenating numbers as strings from right to left
const concatenatedRight = numbers.reduceRight((accumulator, currentValue) => {
  return accumulator + currentValue;
}, '');

console.log(concatenatedRight); // Output: '54321'

reduce가 pipe를 만들 때 유용했다면, reduceRight은 compose를 만들 때 아주 유용합니다. 물론 reduce에 reverse()를 통해 만들수도 있지만 덜 효과적이겠죠.

compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x)
compose(double, add1)(100) // 202

 

 

ProviderComposer를 통해 보는 함수형 프로그래밍

callback hell을 이해하기 어려워 선언적 프로그래밍인 async await을 사용하게 된 것처럼, 우리는 익숙하지만 불편하게 사용했던 nested provider를 reduceRight을 통해 선언형으로 사용할 수 있습니다.

import React, { cloneElement } from 'react';

// import providers
import { ExportedProvider } from './path/to/provider';

function ProviderComposer({ contexts, children }) {
  return contexts.reduceRight(
    (kids, parent) =>
      cloneElement(parent, {
        children: kids,
      }),
    children
  );
}

export function ContextProvider({ children }) {
  return (
    <ProviderComposer
      // add providers to array of contexts
      contexts={
        [
          <ExportedProvider key="exported" />,
          <AnotherExportedProvider key="another-exported" />,
        ]
      }
    >
      {children}
    </ProviderComposer>
  );
}

 

참조

https://medium.com/free-code-camp/10-ways-to-write-pipe-compose-in-javascript-f6d54c575616

https://gist.github.com/devjmetivier/ff3db2e883721c699a3f7608b64eddab

'software engineering > frontend' 카테고리의 다른 글

2024 FE conf  (3) 2024.08.26
React 19 Beta!  (0) 2024.04.29
Preact 그리고 Signals  (0) 2024.02.14
Zustand Persist (부제: localstorage 쉽게 저장하기)  (1) 2024.02.12
Next13 import-meta-env 도입기 그리고 주의점  (1) 2024.02.12