Skip to content

Instantly share code, notes, and snippets.

@timbuckley
Last active December 21, 2017 20:07
Show Gist options
  • Save timbuckley/ab678a692ad1f972397e6c79f299263e to your computer and use it in GitHub Desktop.
Save timbuckley/ab678a692ad1f972397e6c79f299263e to your computer and use it in GitHub Desktop.
Comparing fizzbuzz implementations in Haskell and JavaScript
fizzes = cycle ["", "", "Fizz"]
buzzes = cycle ["", "", "", "", "Buzz"]
fbs = zipWith (++) fizzes buzzes
nums = map show [1..]
fizzbuzz n = take n (zipWith max nums fbs)
-- Usage:
-- fizzbuzz 3
-- -> ["1", "2", "Fizz"]
function* cycle(vals) {
let len = vals.length
let index = 0
while (true) {
yield vals[index % len]
index += 1
}
}
function* zipStreams(...streams) {
while (true) {
yield streams.map(g => g.next().value)
}
}
function* zipStreamsWith(f, ...streams) {
while (true) {
yield streams
.map(g => g.next().value)
.reduce(f)
}
}
function take(n, stream) {
let result = []
for (let i = 0; i < n; i++) {
result.push(stream.next().value)
}
return result
}
function* range(start, stop = Infinity) {
let i = start
while (i < stop) {
yield i
i += 1
}
}
const concat = (a, b) => a + b
const longer = (a, b) => String(a).length > String(b).length ? String(a) : String(b)
const fizzes = cycle(["", "", "fizz"])
const buzzes = cycle(["", "", "", "", "buzz"])
const fbs = zipStreamsWith(concat, fizzes, buzzes)
const nums = range(1)
const fizzBuzz = (n) => take(n, zipStreamsWith(longer, nums, fbs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment