티스토리 뷰

728x90

 

reduceRight

알고리즘 풀다가 처음 알게된 reduceRight 메소드.

메소드이름에서 유추할 수 있듯 배열의 오른쪽에서 왼쪽(right-to-left)로 reduce를 해주는 메소드이다.

 

const fn1 = (x) => x * 2;
const fn2 = (x) => x + 3;
const fn3 = (x) => x - 1;

const compose = (functions) => {
	return (x) => functions.reduceRight((acc, curr) => curr(acc), x);   
}

const func = compose([fn1, fn2, fn3]);
console.log(func(4)); // 12
// reduceRight 첫번째 iteration
// initialValue인 x는 4. 즉 acc가 4
// 배열의 가장 오른쪽에 있는(가장 마지막) 요소인 fn3 함수가 curr(currentValue)가 된다.
// fn3(4) -> 3
// 두번째 iteration
// fn2(3) -> 6
// 세번째 iteration
// fn1(5) -> 12

 

(해당 메소드를 사용하여 해결한 알고리즘 문제)

 

leetcode/2629-function-composition at main · danimkim/leetcode

Contribute to danimkim/leetcode development by creating an account on GitHub.

github.com

 

 

reverse

배열을 역순으로 정렬해주는 메소드. 원본 배열을 변경하는 파괴적 메소드이다.

const arr = ['e', 'l', 'p', 'p', 'a']

arr.reverse();

console.log(arr); // ['a', 'p', 'p', 'l', 'e'];

 

728x90

'Today I Learned' 카테고리의 다른 글

React 간단 개요  (0) 2024.11.18
Vite로 React + TypeScript 프로젝트 생성하기  (0) 2024.08.05
2021-11-16 TIL  (0) 2021.11.16
2021-11-15 TIL  (0) 2021.11.15
2021-11-12 TIL  (2) 2021.11.12