Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
https://repl.it/C3Gl/75 created by km-tr
// https://tech.recruit-mp.co.jp/front-end/post-10358
function range(n) {
return function * f(i) {
if (i < n) {
yield i;
yield* f(i + 1)
}
}(0);
}
console.log(Array.from(range(10)));
function * rangeRepeat(n, c) {
while (c > 0) {
yield* range(n);
c -= 1;
}
}
console.log([...rangeRepeat(5, 3)]);
console.log('問題1 take');
// 関数takeはIteratorとnumberを引数に取り指定された数以下の長さを返すIteratorを返す関数にしてください。ここでいう長さとはnextを読んだときの返り値のdoneがtrueを返すまでの回数です。
function * take(iterator, number) {
for(let next of iterator) {
if (number > 0) {
yield next;
number--;
} else {
return;
}
}
}
console.log(Array.from(take(range(1000), 5))); // -> [0, 1, 2, 3, 4]
console.log(Array.from(take(range(3), 5))); // -> [0, 1, 2]
console.log('問題2 fib');
// フィボナッチ数列を返すようなIteratorを返す関数fibをgeneratorで作ってみてください。
function * fib() {
let current = 1;
let next = 1;
while(true) {
yield current;
[current, next] = [next, current + next];
}
}
console.log(Array.from(take(fib(), 20))); // -> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
console.log('問題3 split word');
// "Hello World Welcome To Generator"のような空白で区切られた文字列を引数に取り、word(空文字列を除く)を1つずつもらえるIteratorを返す関数splitWordを作ってみてください。
function * splitWord(string) {
const result = /(\S+?)(\s.+)?$/.exec(string);
yield result[1];
if (!result[2]) { return; }
yield* splitWord(result[2]);
}
console.log(Array.from(splitWord("Hello World Welcome To Generator"))); // -> ["Hello", "World", "Welcome", "To", "Generator"]
Babel Compiler v6.4.4
Copyright (c) 2014-2015 Sebastian McKenzie
>>> [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
[ 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4 ]
問題1 take
[ 0, 1, 2, 3, 4 ]
[ 0, 1, 2 ]
問題2 fib
[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765 ]
問題3 split word
[ 'Hello World Welcome To Generator',
'Hello',
' World Welcome To Generator',
index: 0,
input: 'Hello World Welcome To Generator' ]
[ 'World Welcome To Generator',
'World',
' Welcome To Generator',
index: 2,
input: ' World Welcome To Generator' ]
[ 'Welcome To Generator',
'Welcome',
' To Generator',
index: 1,
input: ' Welcome To Generator' ]
[ 'To Generator', 'To', ' Generator', index: 1, input: ' To Generator' ]
[ 'Generator', 'Generator', undefined, index: 2, input: ' Generator' ]
[ 'Hello', 'World', 'Welcome', 'To', 'Generator' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.