@faker-js/faker
Version:
Generate massive amounts of fake contextual data
1,957 lines (1,688 loc) • 6.05 MB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.faker = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
// since we are requiring the top level of faker, load all locales by default
var Faker = require('./lib');
var faker = new Faker({ locales: require('./lib/locales') });
module['exports'] = faker;
},{"./lib":19,"./lib/locales":21}],2:[function(require,module,exports){
/**
*
* @namespace faker.address
*/
function Address (faker) {
var f = faker.fake,
Helpers = faker.helpers;
/**
* Generates random zipcode from format. If format is not specified, the
* locale's zip format is used.
*
* @method faker.address.zipCode
* @param {String} format
*/
this.zipCode = function(format) {
// if zip format is not specified, use the zip format defined for the locale
if (typeof format === 'undefined') {
var localeFormat = faker.definitions.address.postcode;
if (typeof localeFormat === 'string') {
format = localeFormat;
} else {
format = faker.random.arrayElement(localeFormat);
}
}
return Helpers.replaceSymbols(format);
}
/**
* Generates random zipcode from state abbreviation. If state abbreviation is
* not specified, a random zip code is generated according to the locale's zip format.
* Only works for locales with postcode_by_state definition. If a locale does not
* have a postcode_by_state definition, a random zip code is generated according
* to the locale's zip format.
*
* @method faker.address.zipCodeByState
* @param {String} state
*/
this.zipCodeByState = function (state) {
var zipRange = faker.definitions.address.postcode_by_state[state];
if (zipRange) {
return faker.datatype.number(zipRange);
}
return faker.address.zipCode();
}
/**
* Generates a random localized city name. The format string can contain any
* method provided by faker wrapped in `{{}}`, e.g. `{{name.firstName}}` in
* order to build the city name.
*
* If no format string is provided one of the following is randomly used:
*
* * `{{address.cityPrefix}} {{name.firstName}}{{address.citySuffix}}`
* * `{{address.cityPrefix}} {{name.firstName}}`
* * `{{name.firstName}}{{address.citySuffix}}`
* * `{{name.lastName}}{{address.citySuffix}}`
* * `{{address.cityName}}` when city name is available
*
* @method faker.address.city
* @param {String} format
*/
this.city = function (format) {
var formats = [
'{{address.cityPrefix}} {{name.firstName}}{{address.citySuffix}}',
'{{address.cityPrefix}} {{name.firstName}}',
'{{name.firstName}}{{address.citySuffix}}',
'{{name.lastName}}{{address.citySuffix}}'
];
if (!format && faker.definitions.address.city_name) {
formats.push('{{address.cityName}}');
}
if (typeof format !== "number") {
format = faker.datatype.number(formats.length - 1);
}
return f(formats[format]);
}
/**
* Return a random localized city prefix
* @method faker.address.cityPrefix
*/
this.cityPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.city_prefix);
}
/**
* Return a random localized city suffix
*
* @method faker.address.citySuffix
*/
this.citySuffix = function () {
return faker.random.arrayElement(faker.definitions.address.city_suffix);
}
/**
* Returns a random city name
*
* @method faker.address.cityName
*/
this.cityName = function() {
return faker.random.arrayElement(faker.definitions.address.city_name);
}
/**
* Returns a random localized street name
*
* @method faker.address.streetName
*/
this.streetName = function () {
var result;
var suffix = faker.address.streetSuffix();
if (suffix !== "") {
suffix = " " + suffix
}
switch (faker.datatype.number(1)) {
case 0:
result = faker.name.lastName() + suffix;
break;
case 1:
result = faker.name.firstName() + suffix;
break;
}
return result;
}
//
// TODO: change all these methods that accept a boolean to instead accept an options hash.
//
/**
* Returns a random localized street address
*
* @method faker.address.streetAddress
* @param {Boolean} useFullAddress
*/
this.streetAddress = function (useFullAddress) {
if (useFullAddress === undefined) { useFullAddress = false; }
var address = "";
switch (faker.datatype.number(2)) {
case 0:
address = Helpers.replaceSymbolWithNumber("#####") + " " + faker.address.streetName();
break;
case 1:
address = Helpers.replaceSymbolWithNumber("####") + " " + faker.address.streetName();
break;
case 2:
address = Helpers.replaceSymbolWithNumber("###") + " " + faker.address.streetName();
break;
}
return useFullAddress ? (address + " " + faker.address.secondaryAddress()) : address;
}
/**
* streetSuffix
*
* @method faker.address.streetSuffix
*/
this.streetSuffix = function () {
return faker.random.arrayElement(faker.definitions.address.street_suffix);
}
/**
* streetPrefix
*
* @method faker.address.streetPrefix
*/
this.streetPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.street_prefix);
}
/**
* secondaryAddress
*
* @method faker.address.secondaryAddress
*/
this.secondaryAddress = function () {
return Helpers.replaceSymbolWithNumber(faker.random.arrayElement(
[
'Apt. ###',
'Suite ###'
]
));
}
/**
* county
*
* @method faker.address.county
*/
this.county = function () {
return faker.random.arrayElement(faker.definitions.address.county);
}
/**
* country
*
* @method faker.address.country
*/
this.country = function () {
return faker.random.arrayElement(faker.definitions.address.country);
}
/**
* countryCode
*
* @method faker.address.countryCode
* @param {string} alphaCode default alpha-2
*/
this.countryCode = function (alphaCode) {
if (typeof alphaCode === 'undefined' || alphaCode === 'alpha-2') {
return faker.random.arrayElement(faker.definitions.address.country_code);
}
if (alphaCode === 'alpha-3') {
return faker.random.arrayElement(faker.definitions.address.country_code_alpha_3);
}
return faker.random.arrayElement(faker.definitions.address.country_code);
}
/**
* state
*
* @method faker.address.state
* @param {Boolean} useAbbr
*/
this.state = function (useAbbr) {
return faker.random.arrayElement(faker.definitions.address.state);
}
/**
* stateAbbr
*
* @method faker.address.stateAbbr
*/
this.stateAbbr = function () {
return faker.random.arrayElement(faker.definitions.address.state_abbr);
}
/**
* latitude
*
* @method faker.address.latitude
* @param {Double} max default is 90
* @param {Double} min default is -90
* @param {number} precision default is 4
*/
this.latitude = function (max, min, precision) {
max = max || 90
min = min || -90
precision = precision || 4
return faker.datatype.number({
max: max,
min: min,
precision: parseFloat((0.0).toPrecision(precision) + '1')
}).toFixed(precision);
}
/**
* longitude
*
* @method faker.address.longitude
* @param {Double} max default is 180
* @param {Double} min default is -180
* @param {number} precision default is 4
*/
this.longitude = function (max, min, precision) {
max = max || 180
min = min || -180
precision = precision || 4
return faker.datatype.number({
max: max,
min: min,
precision: parseFloat((0.0).toPrecision(precision) + '1')
}).toFixed(precision);
}
/**
* direction
*
* @method faker.address.direction
* @param {Boolean} useAbbr return direction abbreviation. defaults to false
*/
this.direction = function (useAbbr) {
if (typeof useAbbr === 'undefined' || useAbbr === false) {
return faker.random.arrayElement(faker.definitions.address.direction);
}
return faker.random.arrayElement(faker.definitions.address.direction_abbr);
}
this.direction.schema = {
"description": "Generates a direction. Use optional useAbbr bool to return abbreviation",
"sampleResults": ["Northwest", "South", "SW", "E"]
};
/**
* cardinal direction
*
* @method faker.address.cardinalDirection
* @param {Boolean} useAbbr return direction abbreviation. defaults to false
*/
this.cardinalDirection = function (useAbbr) {
if (typeof useAbbr === 'undefined' || useAbbr === false) {
return (
faker.random.arrayElement(faker.definitions.address.direction.slice(0, 4))
);
}
return (
faker.random.arrayElement(faker.definitions.address.direction_abbr.slice(0, 4))
);
}
this.cardinalDirection.schema = {
"description": "Generates a cardinal direction. Use optional useAbbr boolean to return abbreviation",
"sampleResults": ["North", "South", "E", "W"]
};
/**
* ordinal direction
*
* @method faker.address.ordinalDirection
* @param {Boolean} useAbbr return direction abbreviation. defaults to false
*/
this.ordinalDirection = function (useAbbr) {
if (typeof useAbbr === 'undefined' || useAbbr === false) {
return (
faker.random.arrayElement(faker.definitions.address.direction.slice(4, 8))
);
}
return (
faker.random.arrayElement(faker.definitions.address.direction_abbr.slice(4, 8))
);
}
this.ordinalDirection.schema = {
"description": "Generates an ordinal direction. Use optional useAbbr boolean to return abbreviation",
"sampleResults": ["Northwest", "Southeast", "SW", "NE"]
};
this.nearbyGPSCoordinate = function(coordinate, radius, isMetric) {
function randomFloat(min, max) {
return Math.random() * (max-min) + min;
}
function degreesToRadians(degrees) {
return degrees * (Math.PI/180.0);
}
function radiansToDegrees(radians) {
return radians * (180.0/Math.PI);
}
function kilometersToMiles(miles) {
return miles * 0.621371;
}
function coordinateWithOffset(coordinate, bearing, distance, isMetric) {
var R = 6378.137; // Radius of the Earth (http://nssdc.gsfc.nasa.gov/planetary/factsheet/earthfact.html)
var d = isMetric ? distance : kilometersToMiles(distance); // Distance in km
var lat1 = degreesToRadians(coordinate[0]); //Current lat point converted to radians
var lon1 = degreesToRadians(coordinate[1]); //Current long point converted to radians
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(d/R) +
Math.cos(lat1) * Math.sin(d/R) * Math.cos(bearing));
var lon2 = lon1 + Math.atan2(
Math.sin(bearing) * Math.sin(d/R) * Math.cos(lat1),
Math.cos(d/R) - Math.sin(lat1) * Math.sin(lat2));
// Keep longitude in range [-180, 180]
if (lon2 > degreesToRadians(180)) {
lon2 = lon2 - degreesToRadians(360);
} else if (lon2 < degreesToRadians(-180)) {
lon2 = lon2 + degreesToRadians(360);
}
return [radiansToDegrees(lat2), radiansToDegrees(lon2)];
}
// If there is no coordinate, the best we can do is return a random GPS coordinate.
if (coordinate === undefined) {
return [faker.address.latitude(), faker.address.longitude()]
}
radius = radius || 10.0;
isMetric = isMetric || false;
// TODO: implement either a gaussian/uniform distribution of points in cicular region.
// Possibly include param to function that allows user to choose between distributions.
// This approach will likely result in a higher density of points near the center.
var randomCoord = coordinateWithOffset(coordinate, degreesToRadians(Math.random() * 360.0), radius, isMetric);
return [randomCoord[0].toFixed(4), randomCoord[1].toFixed(4)];
}
/**
* Return a random time zone
* @method faker.address.timeZone
*/
this.timeZone = function() {
return faker.random.arrayElement(faker.definitions.address.time_zone);
}
return this;
}
module.exports = Address;
},{}],3:[function(require,module,exports){
/**
*
* @namespace faker.animal
*/
var Animal = function (faker) {
var self = this;
/**
* dog
*
* @method faker.animal.dog
*/
self.dog = function() {
return faker.random.arrayElement(faker.definitions.animal.dog);
};
/**
* cat
*
* @method faker.animal.cat
*/
self.cat = function() {
return faker.random.arrayElement(faker.definitions.animal.cat);
};
/**
* snake
*
* @method faker.animal.snake
*/
self.snake = function() {
return faker.random.arrayElement(faker.definitions.animal.snake);
};
/**
* bear
*
* @method faker.animal.bear
*/
self.bear = function() {
return faker.random.arrayElement(faker.definitions.animal.bear);
};
/**
* lion
*
* @method faker.animal.lion
*/
self.lion = function() {
return faker.random.arrayElement(faker.definitions.animal.lion);
};
/**
* cetacean
*
* @method faker.animal.cetacean
*/
self.cetacean = function() {
return faker.random.arrayElement(faker.definitions.animal.cetacean);
};
/**
* horse
*
* @method faker.animal.horse
*/
self.horse = function() {
return faker.random.arrayElement(faker.definitions.animal.horse);
};
/**
* bird
*
* @method faker.animal.bird
*/
self.bird = function() {
return faker.random.arrayElement(faker.definitions.animal.bird);
};
/**
* cow
*
* @method faker.animal.cow
*/
self.cow = function() {
return faker.random.arrayElement(faker.definitions.animal.cow);
};
/**
* fish
*
* @method faker.animal.fish
*/
self.fish = function() {
return faker.random.arrayElement(faker.definitions.animal.fish);
};
/**
* crocodilia
*
* @method faker.animal.crocodilia
*/
self.crocodilia = function() {
return faker.random.arrayElement(faker.definitions.animal.crocodilia);
};
/**
* insect
*
* @method faker.animal.insect
*/
self.insect = function() {
return faker.random.arrayElement(faker.definitions.animal.insect);
};
/**
* rabbit
*
* @method faker.animal.rabbit
*/
self.rabbit = function() {
return faker.random.arrayElement(faker.definitions.animal.rabbit);
};
/**
* type
*
* @method faker.animal.type
*/
self.type = function() {
return faker.random.arrayElement(faker.definitions.animal.type);
};
return self;
};
module['exports'] = Animal;
},{}],4:[function(require,module,exports){
/**
*
* @namespace faker.commerce
*/
var Commerce = function (faker) {
var self = this;
/**
* color
*
* @method faker.commerce.color
*/
self.color = function() {
return faker.random.arrayElement(faker.definitions.commerce.color);
};
/**
* department
*
* @method faker.commerce.department
*/
self.department = function() {
return faker.random.arrayElement(faker.definitions.commerce.department);
};
/**
* productName
*
* @method faker.commerce.productName
*/
self.productName = function() {
return faker.commerce.productAdjective() + " " +
faker.commerce.productMaterial() + " " +
faker.commerce.product();
};
/**
* price
*
* @method faker.commerce.price
* @param {number} min
* @param {number} max
* @param {number} dec
* @param {string} symbol
*
* @return {string}
*/
self.price = function(min, max, dec, symbol) {
min = min || 1;
max = max || 1000;
dec = dec === undefined ? 2 : dec;
symbol = symbol || '';
if (min < 0 || max < 0) {
return symbol + 0.00;
}
var randValue = faker.datatype.number({ max: max, min: min });
return symbol + (Math.round(randValue * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
};
/*
self.categories = function(num) {
var categories = [];
do {
var category = faker.random.arrayElement(faker.definitions.commerce.department);
if(categories.indexOf(category) === -1) {
categories.push(category);
}
} while(categories.length < num);
return categories;
};
*/
/*
self.mergeCategories = function(categories) {
var separator = faker.definitions.separator || " &";
// TODO: find undefined here
categories = categories || faker.definitions.commerce.categories;
var commaSeparated = categories.slice(0, -1).join(', ');
return [commaSeparated, categories[categories.length - 1]].join(separator + " ");
};
*/
/**
* productAdjective
*
* @method faker.commerce.productAdjective
*/
self.productAdjective = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.adjective);
};
/**
* productMaterial
*
* @method faker.commerce.productMaterial
*/
self.productMaterial = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.material);
};
/**
* product
*
* @method faker.commerce.product
*/
self.product = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.product);
};
/**
* productDescription
*
* @method faker.commerce.productDescription
*/
self.productDescription = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_description);
};
return self;
};
module['exports'] = Commerce;
},{}],5:[function(require,module,exports){
/**
*
* @namespace faker.company
*/
var Company = function (faker) {
var self = this;
var f = faker.fake;
/**
* suffixes
*
* @method faker.company.suffixes
*/
this.suffixes = function () {
// Don't want the source array exposed to modification, so return a copy
return faker.definitions.company.suffix.slice(0);
}
/**
* companyName
*
* @method faker.company.companyName
* @param {string} format
*/
this.companyName = function (format) {
var formats = [
'{{name.lastName}} {{company.companySuffix}}',
'{{name.lastName}} - {{name.lastName}}',
'{{name.lastName}}, {{name.lastName}} and {{name.lastName}}'
];
if (typeof format !== "number") {
format = faker.datatype.number(formats.length - 1);
}
return f(formats[format]);
}
/**
* companySuffix
*
* @method faker.company.companySuffix
*/
this.companySuffix = function () {
return faker.random.arrayElement(faker.company.suffixes());
}
/**
* catchPhrase
*
* @method faker.company.catchPhrase
*/
this.catchPhrase = function () {
return f('{{company.catchPhraseAdjective}} {{company.catchPhraseDescriptor}} {{company.catchPhraseNoun}}')
}
/**
* bs
*
* @method faker.company.bs
*/
this.bs = function () {
return f('{{company.bsBuzz}} {{company.bsAdjective}} {{company.bsNoun}}');
}
/**
* catchPhraseAdjective
*
* @method faker.company.catchPhraseAdjective
*/
this.catchPhraseAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.adjective);
}
/**
* catchPhraseDescriptor
*
* @method faker.company.catchPhraseDescriptor
*/
this.catchPhraseDescriptor = function () {
return faker.random.arrayElement(faker.definitions.company.descriptor);
}
/**
* catchPhraseNoun
*
* @method faker.company.catchPhraseNoun
*/
this.catchPhraseNoun = function () {
return faker.random.arrayElement(faker.definitions.company.noun);
}
/**
* bsAdjective
*
* @method faker.company.bsAdjective
*/
this.bsAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.bs_adjective);
}
/**
* bsBuzz
*
* @method faker.company.bsBuzz
*/
this.bsBuzz = function () {
return faker.random.arrayElement(faker.definitions.company.bs_verb);
}
/**
* bsNoun
*
* @method faker.company.bsNoun
*/
this.bsNoun = function () {
return faker.random.arrayElement(faker.definitions.company.bs_noun);
}
}
module['exports'] = Company;
},{}],6:[function(require,module,exports){
/**
*
* @namespace faker.database
*/
var Database = function (faker) {
var self = this;
/**
* column
*
* @method faker.database.column
*/
self.column = function () {
return faker.random.arrayElement(faker.definitions.database.column);
};
self.column.schema = {
"description": "Generates a column name.",
"sampleResults": ["id", "title", "createdAt"]
};
/**
* type
*
* @method faker.database.type
*/
self.type = function () {
return faker.random.arrayElement(faker.definitions.database.type);
};
self.type.schema = {
"description": "Generates a column type.",
"sampleResults": ["byte", "int", "varchar", "timestamp"]
};
/**
* collation
*
* @method faker.database.collation
*/
self.collation = function () {
return faker.random.arrayElement(faker.definitions.database.collation);
};
self.collation.schema = {
"description": "Generates a collation.",
"sampleResults": ["utf8_unicode_ci", "utf8_bin"]
};
/**
* engine
*
* @method faker.database.engine
*/
self.engine = function () {
return faker.random.arrayElement(faker.definitions.database.engine);
};
self.engine.schema = {
"description": "Generates a storage engine.",
"sampleResults": ["MyISAM", "InnoDB"]
};
};
module["exports"] = Database;
},{}],7:[function(require,module,exports){
/**
*
* @namespace faker.datatype
*/
function Datatype (faker, seed) {
// Use a user provided seed if it is an array or number
if (Array.isArray(seed) && seed.length) {
faker.mersenne.seed_array(seed);
}
else if(!isNaN(seed)) {
faker.mersenne.seed(seed);
}
/**
* returns a single random number based on a max number or range
*
* @method faker.datatype.number
* @param {mixed} options {min, max, precision}
*/
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 = 99999;
}
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 = Math.floor(
faker.mersenne.rand(max / options.precision, options.min / options.precision));
// Workaround problem in Float point arithmetics for e.g. 6681493 / 0.01
randomNumber = randomNumber / (1 / options.precision);
return randomNumber;
};
/**
* returns a single random floating-point number based on a max number or range
*
* @method faker.datatype.float
* @param {mixed} options
*/
this.float = function (options) {
if (typeof options === "number") {
options = {
precision: options
};
}
options = options || {};
var opts = {};
for (var p in options) {
opts[p] = options[p];
}
if (typeof opts.precision === 'undefined') {
opts.precision = 0.01;
}
return faker.datatype.number(opts);
};
/**
* method returns a Date object using a random number of milliseconds since 1. Jan 1970 UTC
* Caveat: seeding is not working
*
* @method faker.datatype.datetime
* @param {mixed} options, pass min OR max as number of milliseconds since 1. Jan 1970 UTC
*/
this.datetime = function (options) {
if (typeof options === "number") {
options = {
max: options
};
}
var minMax = 8640000000000000;
options = options || {};
if (typeof options.min === "undefined" || options.min < minMax*-1) {
options.min = new Date().setFullYear(1990, 1, 1);
}
if (typeof options.max === "undefined" || options.max > minMax) {
options.max = new Date().setFullYear(2100,1,1);
}
var random = faker.datatype.number(options);
return new Date(random);
};
/**
* Returns a string, containing UTF-16 chars between 33 and 125 ('!' to '}')
*
*
* @method faker.datatype.string
* @param { number } length: length of generated string, default = 10, max length = 2^20
*/
this.string = function (length) {
if(length === undefined ){
length = 10;
}
var maxLength = Math.pow(2, 20);
if(length >= (maxLength)){
length = maxLength;
}
var charCodeOption = {
min: 33,
max: 125
};
var returnString = '';
for(var i = 0; i < length; i++){
returnString += String.fromCharCode(faker.datatype.number(charCodeOption));
}
return returnString;
};
/**
* uuid
*
* @method faker.datatype.uuid
*/
this.uuid = function () {
var RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
var replacePlaceholders = function (placeholder) {
var random = faker.datatype.number({ min: 0, max: 15 });
var value = placeholder == 'x' ? random : (random &0x3 | 0x8);
return value.toString(16);
};
return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
};
/**
* boolean
*
* @method faker.datatype.boolean
*/
this.boolean = function () {
return !!faker.datatype.number(1);
};
/**
* hexaDecimal
*
* @method faker.datatype.hexaDecimal
* @param {number} count defaults to 1
*/
this.hexaDecimal = function hexaDecimal(count) {
if (typeof count === "undefined") {
count = 1;
}
var wholeString = "";
for(var i = 0; i < count; i++) {
wholeString += faker.random.arrayElement(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
}
return "0x"+wholeString;
};
/**
* returns json object with 7 pre-defined properties
*
* @method faker.datatype.json
*/
this.json = function json() {
var properties = ['foo', 'bar', 'bike', 'a', 'b', 'name', 'prop'];
var returnObject = {};
properties.forEach(function(prop){
returnObject[prop] = faker.datatype.boolean() ?
faker.datatype.string() : faker.datatype.number();
});
return JSON.stringify(returnObject);
};
/**
* returns an array with values generated by faker.datatype.number and faker.datatype.string
*
* @method faker.datatype.array
* @param { number } length of the returned array
*/
this.array = function array(length) {
if(length === undefined){
length = 10;
}
var returnArray = new Array(length);
for(var i = 0; i < length; i++){
returnArray[i] = faker.datatype.boolean() ?
faker.datatype.string() : faker.datatype.number();
}
return returnArray;
};
return this;
}
module['exports'] = Datatype;
},{}],8:[function(require,module,exports){
/**
*
* @namespace faker.date
*/
var _Date = function (faker) {
var self = this;
/**
* past
*
* @method faker.date.past
* @param {number} years
* @param {date} refDate
*/
self.past = function (years, refDate) {
var date = new Date();
if (typeof refDate !== "undefined") {
date = new Date(Date.parse(refDate));
}
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var past = date.getTime();
past -= faker.datatype.number(range); // some time from now to N years ago, in milliseconds
date.setTime(past);
return date;
};
/**
* future
*
* @method faker.date.future
* @param {number} years
* @param {date} refDate
*/
self.future = function (years, refDate) {
var date = new Date();
if (typeof refDate !== "undefined") {
date = new Date(Date.parse(refDate));
}
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var future = date.getTime();
future += faker.datatype.number(range); // some time from now to N years later, in milliseconds
date.setTime(future);
return date;
};
/**
* between
*
* @method faker.date.between
* @param {date} from
* @param {date} to
*/
self.between = function (from, to) {
var fromMilli = Date.parse(from);
var dateOffset = faker.datatype.number(Date.parse(to) - fromMilli);
var newDate = new Date(fromMilli + dateOffset);
return newDate;
};
/**
* betweens
*
* @method faker.date.between
* @param {date} from
* @param {date} to
*/
self.betweens = function (from, to, num) {
if (typeof num == 'undefined') { num = 3; }
var newDates = [];
var fromMilli = Date.parse(from);
var dateOffset = (Date.parse(to) - fromMilli) / ( num + 1 );
var lastDate = from
for (var i = 0; i < num; i++) {
fromMilli = Date.parse(lastDate);
lastDate = new Date(fromMilli + dateOffset)
newDates.push(lastDate)
}
return newDates;
};
/**
* recent
*
* @method faker.date.recent
* @param {number} days
* @param {date} refDate
*/
self.recent = function (days, refDate) {
var date = new Date();
if (typeof refDate !== "undefined") {
date = new Date(Date.parse(refDate));
}
var range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000
};
var future = date.getTime();
future -= faker.datatype.number(range); // some time from now to N days ago, in milliseconds
date.setTime(future);
return date;
};
/**
* soon
*
* @method faker.date.soon
* @param {number} days
* @param {date} refDate
*/
self.soon = function (days, refDate) {
var date = new Date();
if (typeof refDate !== "undefined") {
date = new Date(Date.parse(refDate));
}
var range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000
};
var future = date.getTime();
future += faker.datatype.number(range); // some time from now to N days later, in milliseconds
date.setTime(future);
return date;
};
/**
* month
*
* @method faker.date.month
* @param {object} options
*/
self.month = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.month[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.month[type];
return faker.random.arrayElement(source);
};
/**
* weekday
*
* @param {object} options
* @method faker.date.weekday
*/
self.weekday = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.weekday[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.weekday[type];
return faker.random.arrayElement(source);
};
return self;
};
module['exports'] = _Date;
},{}],9:[function(require,module,exports){
/*
fake.js - generator method for combining faker methods based on string input
*/
function Fake (faker) {
/**
* Generator method for combining faker methods based on string input
*
* __Example:__
*
* ```
* console.log(faker.fake('{{name.lastName}}, {{name.firstName}} {{name.suffix}}'));
* //outputs: "Marks, Dean Sr."
* ```
*
* This will interpolate the format string with the value of methods
* [name.lastName]{@link faker.name.lastName}, [name.firstName]{@link faker.name.firstName},
* and [name.suffix]{@link faker.name.suffix}
*
* @method faker.fake
* @param {string} str
*/
this.fake = function fake (str) {
// setup default response as empty string
var res = '';
// if incoming str parameter is not provided, return error message
if (typeof str !== 'string' || str.length === 0) {
throw new Error('string parameter is required!');
}
// find first matching {{ and }}
var start = str.search('{{');
var end = str.search('}}');
// if no {{ and }} is found, we are done
if (start === -1 && end === -1) {
return str;
}
// console.log('attempting to parse', str);
// extract method name from between the {{ }} that we found
// for example: {{name.firstName}}
var token = str.substr(start + 2, end - start - 2);
var method = token.replace('}}', '').replace('{{', '');
// console.log('method', method)
// extract method parameters
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(method);
var parameters = '';
if (matches) {
method = method.replace(regExp, '');
parameters = matches[1];
}
// split the method into module and function
var parts = method.split('.');
if (typeof faker[parts[0]] === "undefined") {
throw new Error('Invalid module: ' + parts[0]);
}
if (typeof faker[parts[0]][parts[1]] === "undefined") {
throw new Error('Invalid method: ' + parts[0] + "." + parts[1]);
}
// assign the function from the module.function namespace
var fn = faker[parts[0]][parts[1]];
// If parameters are populated here, they are always going to be of string type
// since we might actually be dealing with an object or array,
// we always attempt to the parse the incoming parameters into JSON
var params;
// Note: we experience a small performance hit here due to JSON.parse try / catch
// If anyone actually needs to optimize this specific code path, please open a support issue on github
try {
params = JSON.parse(parameters)
} catch (err) {
// since JSON.parse threw an error, assume parameters was actually a string
params = parameters;
}
var result;
if (typeof params === "string" && params.length === 0) {
result = fn.call(this);
} else {
result = fn.call(this, params);
}
// replace the found tag with the returned fake value
res = str.replace('{{' + token + '}}', result);
// return the response recursively until we are done finding all tags
return fake(res);
}
return this;
}
module['exports'] = Fake;
},{}],10:[function(require,module,exports){
/**
* @namespace faker.finance
*/
var Finance = function (faker) {
var ibanLib = require("./iban");
var Helpers = faker.helpers,
self = this;
/**
* account
*
* @method faker.finance.account
* @param {number} length
*/
self.account = function (length) {
length = length || 8;
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
length = null;
return Helpers.replaceSymbolWithNumber(template);
};
/**
* accountName
*
* @method faker.finance.accountName
*/
self.accountName = function () {
return [Helpers.randomize(faker.definitions.finance.account_type), 'Account'].join(' ');
};
/**
* routingNumber
*
* @method faker.finance.routingNumber
*/
self.routingNumber = function () {
var routingNumber = Helpers.replaceSymbolWithNumber('########');
// Modules 10 straight summation.
var sum = 0;
for (var i = 0; i < routingNumber.length; i += 3) {
sum += Number(routingNumber[i]) * 3;
sum += Number(routingNumber[i + 1]) * 7;
sum += Number(routingNumber[i + 2]) || 0;
}
return routingNumber + (Math.ceil(sum / 10) * 10 - sum);
}
/**
* mask
*
* @method faker.finance.mask
* @param {number} length
* @param {boolean} parens
* @param {boolean} ellipsis
*/
self.mask = function (length, parens, ellipsis) {
//set defaults
length = (length == 0 || !length || typeof length == 'undefined') ? 4 : length;
parens = (parens === null) ? true : parens;
ellipsis = (ellipsis === null) ? true : ellipsis;
//create a template for length
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
//prefix with ellipsis
template = (ellipsis) ? ['...', template].join('') : template;
template = (parens) ? ['(', template, ')'].join('') : template;
//generate random numbers
template = Helpers.replaceSymbolWithNumber(template);
return template;
};
//min and max take in minimum and maximum amounts, dec is the decimal place you want rounded to, symbol is $, €, £, etc
//NOTE: this returns a string representation of the value, if you want a number use parseFloat and no symbol
/**
* amount
*
* @method faker.finance.amount
* @param {number} min
* @param {number} max
* @param {number} dec
* @param {string} symbol
*
* @return {string}
*/
self.amount = function (min, max, dec, symbol, autoFormat) {
min = min || 0;
max = max || 1000;
dec = dec === undefined ? 2 : dec;
symbol = symbol || '';
const randValue = faker.datatype.number({ max: max, min: min, precision: Math.pow(10, -dec) });
let formattedString;
if(autoFormat) {
formattedString = randValue.toLocaleString(undefined, {minimumFractionDigits: dec});
}
else {
formattedString = randValue.toFixed(dec);
}
return symbol + formattedString;
};
/**
* transactionType
*
* @method faker.finance.transactionType
*/
self.transactionType = function () {
return Helpers.randomize(faker.definitions.finance.transaction_type);
};
/**
* currencyCode
*
* @method faker.finance.currencyCode
*/
self.currencyCode = function () {
return faker.random.objectElement(faker.definitions.finance.currency)['code'];
};
/**
* currencyName
*
* @method faker.finance.currencyName
*/
self.currencyName = function () {
return faker.random.objectElement(faker.definitions.finance.currency, 'key');
};
/**
* currencySymbol
*
* @method faker.finance.currencySymbol
*/
self.currencySymbol = function () {
var symbol;
while (!symbol) {
symbol = faker.random.objectElement(faker.definitions.finance.currency)['symbol'];
}
return symbol;
};
/**
* bitcoinAddress
*
* @method faker.finance.bitcoinAddress
*/
self.bitcoinAddress = function () {
var addressLength = faker.datatype.number({ min: 25, max: 34 });
var address = faker.random.arrayElement(['1', '3']);
for (var i = 0; i < addressLength - 1; i++)
address += faker.random.arrayElement('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'.split(''));
return address;
}
/**
* litecoinAddress
*
* @method faker.finance.litecoinAddress
*/
self.litecoinAddress = function () {
var addressLength = faker.datatype.number({ min: 26, max: 33 });
var address = faker.random.arrayElement(['L', 'M', '3']);
for (var i = 0; i < addressLength - 1; i++)
address += faker.random.arrayElement('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'.split(''));
return address;
}
/**
* Credit card number
* @method faker.finance.creditCardNumber
* @param {string} provider | scheme
*/
self.creditCardNumber = function(provider){
provider = provider || "";
var format, formats;
var localeFormat = faker.definitions.finance.credit_card;
if (provider in localeFormat) {
formats = localeFormat[provider]; // there chould be multiple formats
if (typeof formats === "string") {
format = formats;
} else {
format = faker.random.arrayElement(formats);
}
} else if (provider.match(/#/)) { // The user chose an optional scheme
format = provider;
} else { // Choose a random provider
if (typeof localeFormat === 'string') {
format = localeFormat;
} else if( typeof localeFormat === "object") {
// Credit cards are in a object structure
formats = faker.random.objectElement(localeFormat, "value"); // There chould be multiple formats
if (typeof formats === "string") {
format = formats;
} else {
format = faker.random.arrayElement(formats);
}
}
}
format = format.replace(/\//g,"")
return Helpers.replaceCreditCardSymbols(format);
};
/**
* Credit card CVV
* @method faker.finance.creditCardCVV
*/
self.creditCardCVV = function() {
var cvv = "";
for (var i = 0; i < 3; i++) {
cvv += faker.datatype.number({max:9}).toString();
}
return cvv;
};
/**
* ethereumAddress
*
* @method faker.finance.ethereumAddress
*/
self.ethereumAddress = function () {
var address = faker.datatype.hexaDecimal(40).toLowerCase();
return address;
};
/**
* iban
*
* @param {boolean} [formatted=false] - Return a formatted version of the generated IBAN.
* @param {string} [countryCode] - The country code from which you want to generate an IBAN, if none is provided a random country will be used.
* @throws Will throw an error if the passed country code is not supported.
*
* @method faker.finance.iban
*/
self.iban = function (formatted, countryCode) {
var ibanFormat;
if (countryCode) {
var findFormat = function(currentFormat) { return currentFormat.country === countryCode; };
ibanFormat = ibanLib.formats.find(findFormat);
} else {
ibanFormat = faker.random.arrayElement(ibanLib.formats);
}
if (!ibanFormat) {
throw new Error('Country code ' + countryCode + ' not supported.');
}
var s = "";
var count = 0;
for (var b = 0; b < ibanFormat.bban.length; b++) {
var bban = ibanFormat.bban[b];
var c = bban.count;
count += bban.count;
while (c > 0) {
if (bban.type == "a") {
s += faker.random.arrayElement(ibanLib.alpha);
} else if (bban.type == "c") {
if (faker.datatype.number(100) < 80) {
s += faker.datatype.number(9);
} else {
s += faker.random.arrayElement(ibanLib.alpha);
}
} else {
if (c >= 3 && faker.datatype.number(100) < 30) {
if (faker.datatype.boolean()) {
s += faker.random.arrayElement(ibanLib.pattern100);
c -= 2;
} else {
s += faker.random.arrayElement(ibanLib.pattern10);
c--;
}
} else {
s += faker.datatype.number(9);
}
}
c--;
}
s = s.substring(0, count);
}
var checksum = 98 - ibanLib.mod97(ibanLib.toDigitString(s + ibanFormat.country + "00"));
if (checksum < 10) {
checksum = "0" + checksum;
}
var iban = ibanFormat.country + checksum + s;
return formatted ? iban.match(/.{1,4}/g).join(" ") : iban;
};
/**
* bic
*
* @method faker.finance.bic
*/
self.bic = function () {
var vowels = ["A", "E", "I", "O", "U"];
var prob = faker.datatype.number(100);
return Helpers.replaceSymbols("???") +
faker.random.arrayElement(vowels) +
faker.random.arrayElement(ibanLib.iso3166) +
Helpers.replaceSymbols("?") + "1" +
(prob < 10 ?
Helpers.replaceSymbols("?" + faker.random.arrayElement(vowels) + "?") :
prob < 40 ?
Helpers.replaceSymbols("###") : "");
};
/**
* description
*
* @method faker.finance.transactionDescription
*/
self.transactionDescription = function() {
var transaction = Helpers.createTransaction();
var account = transaction.account;
var amount = transaction.amount;
var transactionType = transaction.type;
var company = transaction.business;
var card = faker.finance.mask();
var currency = faker.finance.currencyCode();
return transactionType + " transaction at " + company + " using card ending with ***" + card + " for " + currency + " " + amount + " in account ***" + account
};
};
module['exports'] = Finance;
},{"./iban":14}],11:[function(require,module,exports){
/**
* @namespace faker.git
*/
var Git = function(faker) {
var self = this;
var f = faker.fake;
var hexChars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
/**
* branch
*
* @method faker.git.branch
*/
self.branch = function() {
var noun = faker.hacker.noun().replace(' ', '-');
var verb = faker.hacker.verb().replace(' ', '-');
return noun + '-' + verb;
}
/**
* commitEntry
*
* @method faker.git.commitEntry
* @param {object} options
*/
self.commitEntry = function(options) {
options = options || {};
var entry = 'commit {{git.commitSha}}\r\n';
if (options.merge || (faker.datatype.number({ min: 0, max: 4 }) === 0)) {
entry += 'Merge: {{git.shortSha}} {{git.shortSha}}\r\n';
}
entry += 'Author: {{name.firstName}} {{name.lastName}} <{{internet.email}}>\r\n';
entry += 'Date: ' + faker.date.recent().toString() + '\r\n';
entry += '\r\n\xa0\xa0\xa0\xa0{{git.commitMessage}}\r\n';
return f(entry);
};
/**
* commitMessage
*
* @method faker.git.commitMessage
*/
self.commitMessage = function() {
var format = '{{hacker.verb}} {{hacker.adjective}} {{hacker.noun}}';
return f(format);
};
/**
* commitSha
*
* @method faker.git.commitSha
*/
self.commitSha = function() {
var commit = "";
for (var i = 0; i < 40; i++) {
commit += faker.random.arrayElement(hexChars);
}
return commit;
};
/**
* shortSha
*
* @method faker.git.shortSha
*/
self.shortSha = function() {
var shortSha = "";
for (var i = 0; i < 7; i++) {
shortSha += faker.random.arrayElement(hexChars);
}
return shortSha;
};
return self;
}
module['exports'] = Git;
},{}],12:[function(require,module,exports){
/**
*
* @namespace faker.hacker
*/
var Hacker = function (faker) {
var self = this;
/**
* abbreviation
*
* @method faker.hacker.abbreviation
*/
self.abbreviation = function () {
return faker.random.arrayElement(faker.definitions.hacker.abbreviation);
};
/**
* adjective
*
* @method faker.hacker.adjective
*/
self.adjective = function () {
return faker.random.arrayElement(faker.definitions.hacker.adjective);
};
/**
* noun
*
* @method faker.hacker.noun
*/
self.noun = function () {
return faker.random.arrayElement(faker.definitions.hacker.noun);
};
/**
* verb
*
* @method faker.hacker.verb
*/
self.verb = function () {
return faker.random.arrayElement(faker.definitions.hacker.verb);
};
/**
* ingverb
*
* @method faker.hacker.ingverb
*/
self.ingverb = function () {
return faker.random.arrayElement(faker.definitions.hacker.ingverb);
};
/**
* phrase
*
* @method faker.hacker.phrase
*/
self.phrase = function () {
var data = {
abbreviation: self.abbreviation,
adjective: self.adjective,
ingverb: self.ingverb,
noun: self.noun,
verb: self.verb
};
var phrase = faker.random.arrayElement(faker.definitions.hacker.phrase);
return faker.helpers.mustache(phrase, data);
};
return self;
};
module['exports'] = Hacker;
},{}],13:[function(require,module,exports){
/**
*
* @namespace faker.helpers
*/
var Helpers = function (faker) {
var self = this;
/**
* backward-compatibility
*
* @method faker.helpers.randomize
* @param {array} array
*/
self.randomize = function (array) {
array = array || ["a", "b", "c"];
return faker.random.arrayElement(array);
};
/**
* slugifies string
*
* @method faker.helpers.slugify
* @param {string} string
*/
self.slugify = function (string) {
string = string || "";
return string.replace(/ /g, '-').replace(/[^\一-龠\ぁ-ゔ\ァ-ヴー\w\.\-]+/g, '');
};
/**
* parses string for a symbol and replace it with a random number from 1-10
*
* @method faker.helpers.replaceSymbolWithNumber
* @param {string} string
* @param {string} symbol defaults to `"#"`
*/
self.replaceSymbolWithNumber = function (string, symbol) {
string = string || "";
// default sym