Fizz Buzz | LeetCode 412 (Three Methods)

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard


Here is the full implementation.

Method 1

let fizzBuzz = function(n) {
  let result = [];

  for (let i = 1; i <= n; i++) {
    if (i % 15 === 0) {
      result.push('FizzBuzz');
    } else if (i % 5 === 0) {
      result.push('Buzz');
    } else if (i % 3 === 0) {
      result.push('Fizz');
    } else {
      result.push(i.toString());
    }
  }

  return result;
};

Method 2

let fizzBuzz = function(n) {
  let result = [];

  for (let i = 1; i <= n; i++) {
    let str = '';

    if (i % 3 === 0) {
      str += 'Fizz';
    }

    if (i % 5 === 0) {
      str += 'Buzz';
    }

    if (!str) {
      str += i;
    }

    result.push(str);
  }

  return result;
};

Method 3

let fizzBuzz = function(n) {
  let result = [];
  
  let mappings = {
    3: 'Fizz',
    5: 'Buzz'
  };

  for (let i = 1; i <= n; i++) {
    let str = '';

    for (let key in mappings) {
      if (i % parseInt(key, 10) === 0) {
        str += mappings[key];
      }
    }

    if (!str) {
      str += i;
    }

    result.push(str);
  }

  return result;
};