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

Javascript

Using a generator function to calculate the successive years

function nbYear(p0, percent, aug, p) { let i, population = pop(p0, percent / 100, aug); for (i = 0; population.next().value < p; i++); return i; } function * pop(p, r, ann) { while (true) { yield p; p += p * r + ann; } }

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 }

Javascript

Using a generator function to calculate the successive years

If you're using generators, go wild :v

or at least

(even though the following is actually shorter)