Skip to content

Instantly share code, notes, and snippets.

@indongyoo
Last active May 28, 2020 09:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save indongyoo/adb45774db1124046d5f053d9539ba71 to your computer and use it in GitHub Desktop.
Save indongyoo/adb45774db1124046d5f053d9539ba71 to your computer and use it in GitHub Desktop.
김동현님 질문 코드
function* filter(f, iter) {
for (const a of iter) if (f(a)) yield a;
}
function* take(limit, iter) {
for (const a of iter) if (limit--) yield a;
}
const head = iter => take(1, iter).next().value;
const find = (f, iter) => head(filter(f, iter));
function* map(f, iter) {
for (const a of iter) yield f(a);
}
const zipWithCount = (iter, cnt = 1) => map(a => [a, cnt++], iter);
function* infinity(f, acc) {
while (true) yield (acc = f(acc));
}
const isOdd = a => a % 2;
const calc = a => isOdd(a) ? a * 3 + 1 : a / 2;
const iter = zipWithCount(infinity(calc, 1));
console.log(iter.next().value); // [4, 1]
console.log(iter.next().value); // [2, 2]
console.log(iter.next().value); // [1, 3]
console.log(iter.next().value); // [4, 4]
console.log(iter.next().value); // [2, 5]
const [num, count] =
find(([a]) => a == 1,
zipWithCount(
infinity(calc, 1)));
console.log(num, count); // 1, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment