skip to Main Content

I want to create a function that logs out "I have 1 bottle. I have 2 bottles. I have 3 bottles" and so on, to the console.
But I keep getting the output below:

I have 1 bottle
I have 1 bottle,bottle
I have 1 bottle,bottle,bottle
let word = []

function test() {
  let x = 1
  if (x <= 1) {
    word.push("bottle")
    console.log("I have " + x + " " + word)
  } else if (x > 1) {
    word.push("bottles")
    console.log("I have " + x + " " + word)
  }

  x++
}

test()
test()
test()

2

Answers


  1. let word = []
    let x = 1
    
    function test() {
      if (x === 1) {
        word.push("bottle")
        console.log("I have " + x + " " + word.join(", "))
      } else if (x > 1) {
        word.push("bottles")
        console.log("I have " + x + " " + word.join(", "))
      }
    
      x++
    }
    
    test()
    test()
    test()

    like that ?

    Login or Signup to reply.
  2. This is a perfect use case for a generator.

    const pluralRules = new Intl.PluralRules('en-US');
    
    function pluralize(count, singular, plural) {
      const rule = pluralRules.select(count);
      switch (rule) {
        case 'one'   : return `${count} ${singular}`;
        case 'other' : return `${count} ${plural ?? singular + 's'}`;
        default      : throw new Error(`Unknown: ${rule}`);
      }
    }
    
    function* bottleGenerator() {
      let count = 0;
      while (true) {
        yield `I have ${pluralize(++count, 'bottle')}`;
      }
    };
    
    const gen = bottleGenerator();
    
    for (let i = 0; i < 3; i++) {
      console.log(gen.next().value);
    }

    Here is a more quick-and-dirty-approach:

    const bottleGenerator = function* () {
      yield `I have 1 bottle`;
      let count = 1;
      while (true) yield `I have ${++count} bottles`;
    };
    
    const gen = bottleGenerator();
    for (let i = 0; i < 3; i++) {
      console.log(gen.next().value);
    }

    And here is an alternative that uses an enhanced for-loop:

    const bottleGenerator = function* () {
      yield `I have 1 bottle`;
      let count = 1;
      while (true) yield `I have ${++count} bottles`;
    };
    
    let limit = 3;
    for (let value of bottleGenerator()) {
      console.log(value);
      if (--limit <= 0) break; // Exit
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search