Last active
September 4, 2015 14:31
-
-
Save jminuscula/698c6a72f9e89bd12353 to your computer and use it in GitHub Desktop.
ES6 generators test
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
"use strict"; | |
(function() { | |
function* map(iterable, fn) { | |
for (let item of iterable) { | |
yield fn(item); | |
} | |
} | |
function* cycle(generator) { | |
let iter = generator(); | |
while (true) { | |
let item = iter.next(); | |
if (item.done) { | |
iter = generator(); | |
continue; | |
} | |
yield item.value; | |
} | |
} | |
function* waveFn(config) { | |
let x = 0; | |
while (true) { | |
x++; | |
let B = (2 * Math.PI) / config.period; | |
let A = config.amplitude * Math.cos((B * x) / config.variation); | |
let D = config.vShift; | |
let y = A * Math.sin(B * x) + D; | |
yield Math.round(y); | |
} | |
} | |
function* numRange(start, end) { | |
for (let n = start; n < end; n++) { | |
yield n; | |
} | |
} | |
function* abcRange() { | |
function abcGenerator() { | |
let chr = n => String.fromCharCode((n % 26) + 65); | |
return map(numRange(0, 26), chr); | |
} | |
yield* cycle(abcGenerator); | |
} | |
function* zip(a, b) { | |
while (true) { | |
let aValue = a.next(), | |
bValue = b.next(); | |
if (aValue.done || bValue.done) { | |
return; | |
} | |
yield [aValue.value, bValue.value]; | |
} | |
} | |
function scheduleNext(iterable, ms) { | |
let advance = iterable => iterable && iterable.next(); | |
setInterval(advance, ms, iterable); | |
} | |
function generateWave() { | |
function printWave(f_C) { | |
let n = f_C[0], | |
c = f_C[1], | |
space = 100; | |
if (n < 0) { | |
space -= Math.abs(n); | |
} | |
process.stdout.write(' '.repeat(space)); | |
console.log(c.repeat(Math.abs(n))); | |
} | |
let sine = waveFn({amplitude: 75, variation: 1.5, period: 50, vShift: 0}), | |
letters = abcRange(), | |
wave = zip(sine, letters), | |
pausedWave = scheduleNext(map(wave, printWave), 50); | |
scheduleNext(); | |
} | |
generateWave(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment