Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FxJS의 map 같은 함수에서 index를 사용하고 싶다면 어떻게 해야할까요? #1

Closed
indongyoo opened this issue Jan 6, 2019 · 2 comments

Comments

@indongyoo
Copy link
Member

indongyoo commented Jan 6, 2019

FxJS의 map 같은 함수에서 index를 두번째 인자로 넘겨주는 부분이 없는데요. 이 부분은 커링이라던지 인자가 여러개 넘어가서 발생하는 문제를 없애려고 그러신건가요?! index 를 쓰고 싶은 경우에는 혹시 어떻게 처리를 하나요?

(페메로 주신 질문입니다.)

@indongyoo
Copy link
Member Author

넵. 커링 문제도 있고, 간결하게 함수 표현을 하기 위해서이기도하고, 함수형 프로그래밍과 i 값 증가가 좀 안어울리기도 하는 부분 등이 있습니다.

이번 버전에서 이렇게 하기로한 또 큰 이유 중에 하나는 ES6+에서는 제너레이터와 구조분해가 있기 때문이기도 합니다. 이런 부분들에 대해서는 아래 코드들을 보시면 답변이 될 것 같습니다. index 사용 사례도 함께 있습니다.

감사합니다.

const log = console.log;

log(['1', '3', '5'].map(a => parseInt(a)));
// [1, 3, 5]

log(['1', '3', '5'].map(parseInt));
// [1, NaN, NaN]

const L = {};
L.map = function *(f, iter) {
  for (const a of iter) yield f(a);
};
L.entries = function *(obj) {
  for (const k in obj) yield [k, obj[k]];
};

log([...L.map(parseInt, ['1', '3', '5'])]);
// [1, 3, 5]

log([...L.map(
  ([i, a]) => `${i}: ${parseInt(a) * 2}`,
  L.entries(['1', '3', '5']))]);
// ["0: 2", "1: 6", "2: 10"]
import { log, map, L } from '../fx.js';

const list = [1, 2, 3];
log(map(a => a + 1, list));
// [2, 3, 4]
log(map(([i, a]) => `${i} - ${a + 1}`, L.entries(list)));
// ["0 - 2", "1 - 3", "2 - 4"]

L.indexValues = function*(iter) {
  let i = -1;
  for (const a of iter) yield [++i, a];
};

log(map(([i, a]) => [i, a], L.indexValues([10, 20, 30])));

@indongyoo
Copy link
Member Author

해당 내용 영상으로도 답변을 만들어보았습니다.

영상 보기 - https://youtu.be/wI-XHysmyRA

감사합니다 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant