FizzBuzz (v2)

Revision 2 of this benchmark created on


Description

Как это можно переписать? https://www.youtube.com/watch?v=m7LmAdFI-QY https://www.youtube.com/live/MSLHs4z6sE4

Setup

const N = 10_000_000;
let bh = 0;

function vFizzBuzz1(n) {
  const r = []
  for(let i1 = 1, i3 = 0, i5 = 0; i1 <= n; i1++) {
    if(i1 - i3 === 3) i3 = i1
    if(i1 - i5 === 5) i5 = i1
    let s = ''
    if(i1 === i3) s += 'Fizz'
    if(i1 === i5) s += 'Buzz'
    r.push(s || i1)
  }

  return r
}

function vFizzBuzz2(n) {
  const r = new Array(n)
  for(let i1 = 1, i3 = 0, i5 = 0; i1 <= n; i1++) {
    if(i1 - i3 === 3) i3 = i1
    if(i1 - i5 === 5) i5 = i1

    if(i1 === i3 && i1 === i5) r.push('FizzBuzz')
	else if(i1 === i3) r.push('Fizz')
	else if(i1 === i5) r.push('Buzz')
	else r.push(i1)
  }

  return r
}

function fizzbuzz1(n) {
  const r = [];
  for (let i = 1; i < n; i++) {
    const isFizz = i % 3 === 0;
    const isBuzz = i % 7 === 0;

    if (isFizz && isBuzz) {
      r.push('FizzBuzz');
    } else if (isFizz) {
      r.push('Fizz');
    } else if (isBuzz) {
      r.push('Buzz');
    } else {
      r.push(i);
    }
  }
  return r;
}

function fizzbuzz3(n) {
  const r = new Array(n);
  for (let i = 1; i < n; i++) {
    const isFizz = i % 3 === 0;
    const isBuzz = i % 7 === 0;

    if (isFizz && isBuzz) {
      r[i] = 'FizzBuzz';
    } else if (isFizz) {
      r[i] = 'Fizz';
    } else if (isBuzz) {
      r[i] = 'Buzz';
    } else {
      r[i] = i;
    }
  }
  return r;
}

function fizzbuzz2(n) {
  const r = [];
  let i = 1;
  while (i <= n - 21) {
    r.push(i, i + 1, 'Fizz', i + 3, i + 4, 'Fizz', 'Buzz', i + 7, 'Fizz', i + 9, i + 10, 'Fizz', i + 12, 'Buzz', 'Fizz', i + 15, i + 16, 'Fizz', i + 18, i + 19, 'FizzBuzz');
    i += 21;
  }

  while (i <= n) {
    if (i % 3 === 0 && i % 7 === 0) {
      r.push('FizzBuzz');
    } else if (i % 3 === 0) {
      r.push('Fizz');
    } else if (i % 7 === 0) {
      r.push('Buzz');
    } else {
      r.push(i);
    }
  i++;
  }
  return r;
}

var typeFizzBuzz = len => {
	var a = new Array(len);
	return (step, name) => {
		for (let i = step; i < len; i += step) {
			a[i] += name
		}
		return a
	}
};

Teardown

if (Math.random() > 1) {
	console.log(bh);
}

Test runner

Ready to run.

Testing in
TestOps/sec
veged-1
bh += vFizzBuzz1(N).length;
ready
veged-2
bh += vFizzBuzz2(N).length;
ready
victor-homyakov-1
bh += fizzbuzz1(N).length;
ready
victor-homyakov-2
bh += fizzbuzz2(N).length;
ready
victor-homyakov-3
bh += fizzbuzz3(N).length;
ready
as-for-js
var doFizzBuzz = typeFizzBuzz(N);
var theBuzz = doFizzBuzz(3, 'Fizz');
var theFinal = doFizzBuzz(7, 'Buzz');
for (let i = 0; i < N; i++) {
	theFinal[i] = theFinal[i] || i;
}
bh += theFinal.length;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.