Hacker News new | past | comments | ask | show | jobs | submit login

It is exactly the way I'm thinking. More importantly, the order of the digits doesn't matter, so if 12 is divisible, so is 21, 102, etc.

Though maybe the two approaches can be combined




Sure maybe something like this. It's not very performant, but it uses some math skills:

  console.clear();

  /** naive python like range in JS */
  function* range (beg, end) {
    for(let i = beg; i < end; ++i) {
      // stringify the number
      yield '' + i;
    }
  }
  
  function buzz (stringNum) {
    const lastChar = stringNum.charAt(stringNum.length - 1);
    return lastChar === '5' || lastChar === '0';
  }
  
  const mapping = [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1];
  
  function fizz (stringNum) {
    return (
      stringNum
        // get each character of the string
        .split('')
        // find out if total digits are divisible by three.
        .reduce((acc, x) => (acc + mapping[x]) % 3, 0) === 0
    );
  }
  
  function fizzBuzz (stringNum) {
    const f = fizz(stringNum), b = buzz(stringNum);
    if(f && b) {
      return 'FizzBuzz';
    } else if (f) {
      return 'Fizz';
    } else if (b) {
      return 'Buzz';
    } else {
      return stringNum;
    }
  }
  
  const nums = [...range(1,1001)];
  
  const result = nums
    // main algo
    .map(fizzBuzz)
  
  console.log(result.join('\n'));
EDIT: sorry I didn't see your other reply below another comment. I now see this does not fulfill the requirements.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: