DEV Community

Discussion on: Daily Challenge #271 - Simulate Population Growth

Collapse
dry profile image
Hayden Mankin

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;
  }
}
Collapse
qm3ster profile image
Mihail Malo • Edited on

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
}