Nodejs Array Sample sample(n)

Here you can find the source of sample(n)

Method Source Code

"use strict";/*from   www  .ja  v a 2s .  com*/

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;
};

Related

  1. sample()
    Array.prototype.sample = function(){
      return this[Math.floor(Math.random()*this.length)];
    
  2. sample()
    Array.prototype.sample = function() {
      var rand_position = parseInt(Math.random() * this.length);
      return this[rand_position];
    };
    
  3. sample()
    Array.prototype.sample = function() {
        return this[Math.floor(Math.random() * this.length)];
    };
    function Duck(color){
      this.type = color;
      this.quack = function() {
        console.log(["Quacksicles!","Quacktacular!","That's so QUACK!"].sample());
      };
    var redDuck = new Duck("red");
    var yellowDuck = new Duck("yellow");
    console.log("The " + redDuck.type + " duck says: ");
    redDuck.quack();
    console.log("The " + yellowDuck.type + " duck says: ");
    yellowDuck.quack();
    
  4. sample()
    Array.prototype.sample = function() {
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min)) + min;
        return this[getRandomInt(0, this.length)];
    
  5. sample(n)
    Array.prototype.sample = function(n) {
      const result = [...this];
      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());
    
  6. sample(n)
    Array.prototype.sample = function(n) {
      const result = this.slice();
      const count = Math.min(n, result.length);
      for (let i = 0 ; i < count ; i++) {
        const x = Math.floor(Math.random() * result.length);
        const temp = result[i];
        result[i] = result[x];
        result[x] = temp;
      return result.slice(0, count);
    
  7. sample(n)
    Array.prototype.sample = function(n){
      if (typeof n == "undefined") n = 1
      results = []
      for (var i = 0; i < n; i++){
        results.push(this[Math.floor(Math.random()*this.length)])
      return results