Javascript Array sample(n)

Description

Javascript Array sample(n)


/* ECMAScript 2015 */

Array.prototype.sample = function(n) {
  const result = [...this];//from   w  ww.ja  v a2 s .co  m
  const count = Math.min(n, result.length);

  for (let i = 0 ; i < count ; i++) {
    const x = Math.floor(Math.random() * result.length);

    [result[i], result[x]] = [result[x], result[i]];
  }

  return result.slice(0, count);
}

const generate = () =>
  Array(45).fill()
           .map((_, i) => i + 1)
           .sample(6)
           .sort((x, y) => x - y)
           .join(', ');

console.log(generate());

Javascript Array sample(n)

"use strict";/*from   ww w . ja  va  2s  . c  om*/

Array.prototype.sample = function (n) {
  var randNum, dupe, result;
  if (arguments.length === 0) {
    result = this[Math.floor(Math.random()*this.length)];
  } else if (parseInt(n) !== n) {
    throw TypeError("argument must be a number");
  } else if (n <= 0) {
    throw RangeError("argument must greater than zero");
  } else {
    n = n > this.length ? this.length : n;
    dupe = this.slice();
    result = [];
    for(var i=0; i<n; i++) {
      randNum = Math.floor(Math.random()*dupe.length);
      result.push(dupe[randNum]);
      dupe.splice(randNum, 1);
    }
  }
  return result;
};



PreviousNext

Related