Created
June 18, 2016 04:31
-
-
Save delphinus/3084edab52a2c3ebd5909f9f8a8ed63b to your computer and use it in GitHub Desktop.
Javascript Generator のテスト
This file contains 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 range(n) { | |
let value = 0; | |
return { | |
next() { | |
if (value < n) { | |
const result = {value, done: false}; | |
value += 1; | |
return result; | |
} | |
return {value: undefined, done: true}; | |
}, | |
[Symbol.iterator]() { | |
return this; | |
} | |
}; | |
} | |
function * rangeGen(n) { | |
let i = 0; | |
while (i < n) { | |
yield i; | |
i += 1; | |
} | |
} | |
function * rangeRepeat(n, c) { | |
while (c > 0) { | |
yield* rangeGen(n); | |
c -= 1; | |
} | |
} | |
function * take(iter, n) { | |
let i = 0; | |
while (i < n) { | |
const j = iter.next(); | |
if (j.done) { | |
break; | |
} else { | |
i += 1; | |
yield j.value; | |
} | |
} | |
} | |
function * fib() { | |
let i = 1; | |
let j = 1; | |
while (true) { | |
const current = i; | |
i = j; | |
j = current + i; | |
yield current; | |
} | |
} | |
function * splitWord(sentence) { | |
} | |
function * gfn() { | |
const a = yield 0; | |
yield* [1, a, 5]; | |
} | |
function * randomIntArray(max, length) { | |
for (let i of rangeGen(length)) { | |
yield Math.floor(Math.random() * max) + 1; | |
} | |
} | |
function * combination(ary, len) { | |
yield * (function * gfn(a, ary){ | |
if (a.length < len) { | |
for (let i of rangeGen(ary.length - len + a.length + 1)) { | |
yield * gfn([...a, ...ary[i]], ary.slice(i + 1)); | |
} | |
} else { | |
yield a; | |
} | |
})([], ary); | |
} | |
function easyAsync(gfn) { | |
const g = gfn(); | |
(function ok(value) { | |
const result = g.next(value); | |
if (! result.done) { | |
result.value(ok); | |
} | |
})(); | |
} | |
easyAsync(function*() { | |
console.log('hello!'); | |
yield ok => setTimeout(ok, 3000); | |
console.log('3 seconds!'); | |
yield ok => document.onclick = ok; | |
document.onclick = null; | |
console.log('document clicked!'); | |
const source = yield ok => { | |
const xhr = new XMLHttpRequest(); | |
xhr.open('GET', location.href, true); | |
xhr.send(null); | |
xhr.onload = () => ok(xhr.responseText); | |
}; | |
console.log(`The length of the page source is ${source.length} bytes.`); | |
}); | |
console.log(Array.from(take(rangeGen(100), 5))); | |
console.log(Array.from(take(rangeGen(3), 5))); | |
console.log(Array.from(take(fib(), 20))); | |
console.log(Array.from(randomIntArray(6,10))); | |
for (let v of combination([..."ABCDE"], 3)) { | |
console.log(v.join("")); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment