aboutsummaryrefslogtreecommitdiff
path: root/lib/random.js
blob: 7d5928490ab13da93530a86766920ca491048a7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
var mersenne = require('../vendor/mersenne');

function Random (faker) {
  
  // returns a single random number based on a max number or range
  this.number = function (options) {

      if (typeof options === "number") {
        options = {
          max: options
        };
      }

      options = options || {};

      if (typeof options.min === "undefined") {
        options.min = 0;
      }

      if (typeof options.max === "undefined") {
        options.max = 1;
      }
      if (typeof options.precision === "undefined") {
        options.precision = 1;
      }

      // Make the range inclusive of the max value
      var max = options.max;
      if (max >= 0) {
        max += options.precision;
      } 
        
      var randomNumber = options.precision * Math.floor(
        mersenne.rand(max / options.precision, options.min / options.precision));

      return randomNumber;

  }
  
  // takes an array and returns a random element of the array
  this.array_element = function (array) {
      array = array || ["a", "b", "c"];
      var r = faker.random.number({ max: array.length - 1 });
      return array[r];
  }

  // takes an object and returns the randomly key or value
  this.object_element = function (object, field) {
      object = object || {};
      var array = Object.keys(object);
      var key = faker.random.array_element(array);

      return field === "key" ? key : object[key];
  }

  this.uuid = function () {
      var RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
      var replacePlaceholders = function (placeholder) {
          var random = Math.random()*16|0;
          var value = placeholder == 'x' ? random : (random &0x3 | 0x8);
          return value.toString(16);
      };
      return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
  }

  this.boolean =function () {
      return !!faker.random.number(1)
  }

  return this;
  
}

module['exports'] = Random;



// module.exports = random;