-
-
Save enshahar/a3ec1abe0b7e2f9c78b6bc8428a5cf2d to your computer and use it in GitHub Desktop.
김동현님 질문 코드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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