## DEV Community is a community of 665,273 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Discussion on: Daily Challenge #271 - Simulate Population Growth

## Replies for: Javascript Using a generator function to calculate the successive years function nbYear(p0, percent, aug, p) { let i, population = pop(p0, pe...

If you're using generators, go wild :v

``````const chain = (...fns) => x => fns.reduce((x, fn) => fn(x), x)
const count = it => {
let i = 0
for (_ of it) i++
return i
}
const takeWhile = fn => function * takeWhile(it) {
for (x of it) {
if (!fn(x)) break
yield x
}
}

function * pop(p, r, ann) {
while (true) {
yield p
p += p * r + ann
}
}

const nbYear = (p0, percent, aug, p) => chain(
takeWhile(x => x < p),
count,
)(pop(p0, percent / 100, aug))
``````

or at least

``````function nbYear(p0, percent, aug, p) {
const population = pop(p0, percent / 100, aug)
let i = 0
for (pop of population) {
if (pop > p) return i
i++
}
}
``````

(even though the following is actually shorter)

``````function nbYear(p0, percent, aug, p) {
const population = pop(p0, percent / 100, aug)
let i = 0
while (population.next().value < p) i++
return i
}
``````