UNPKG

faker

Version:

Generate massive amounts of fake contextual data

1,844 lines (1,605 loc) 4.85 MB
(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":17,"./lib/locales":19}],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.random.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}}` * * @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 (typeof format !== "number") { format = faker.random.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 localized street name * * @method faker.address.streetName */ this.streetName = function () { var result; var suffix = faker.address.streetSuffix(); if (suffix !== "") { suffix = " " + suffix } switch (faker.random.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.random.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.random.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.random.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 abbrevation", "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 abbrevation", "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 abbrevation", "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.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.random.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; },{}],4:[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.random.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; },{}],5:[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; },{}],6:[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.random.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.random.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.random.number(Date.parse(to) - fromMilli); var newDate = new Date(fromMilli + dateOffset); return newDate; }; /** * 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.random.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.random.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; },{}],7:[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; },{}],8:[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) { min = min || 0; max = max || 1000; dec = dec === undefined ? 2 : dec; symbol = symbol || ''; var randValue = faker.random.number({ max: max, min: min, precision: Math.pow(10, -dec) }); var stringNumber = symbol + randValue.toFixed(dec); return Number(stringNumber); }; /** * 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.random.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.random.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.random.number({max:9}).toString(); } return cvv; }; /** * ethereumAddress * * @method faker.finance.ethereumAddress */ self.ethereumAddress = function () { var address = faker.random.hexaDecimal(40).toLowerCase(); return address; }; /** * iban * * @method faker.finance.iban */ self.iban = function (formatted) { var ibanFormat = faker.random.arrayElement(ibanLib.formats); 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.random.number(100) < 80) { s += faker.random.number(9); } else { s += faker.random.arrayElement(ibanLib.alpha); } } else { if (c >= 3 && faker.random.number(100) < 30) { if (faker.random.boolean()) { s += faker.random.arrayElement(ibanLib.pattern100); c -= 2; } else { s += faker.random.arrayElement(ibanLib.pattern10); c--; } } else { s += faker.random.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.random.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 account = Helpers.createTransaction().account var card = faker.finance.mask(); var currency = faker.finance.currencyCode(); var amount = Helpers.createTransaction().amount var transactionType = Helpers.createTransaction().type var company = Helpers.createTransaction().business return transactionType + " transaction at " + company + " using card ending with ***" + card + " for " + currency + " " + amount + " in account ***" + account } }; module['exports'] = Finance; },{"./iban":12}],9:[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.random.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; },{}],10:[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; },{}],11:[function(require,module,exports){ /** * * @namespace faker.helpers */ var Helpers = function (faker) { var self = this; /** * backword-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 symbol is '#' if (symbol === undefined) { symbol = '#'; } var str = ''; for (var i = 0; i < string.length; i++) { if (string.charAt(i) == symbol) { str += faker.random.number(9); } else if (string.charAt(i) == "!"){ str += faker.random.number({min: 2, max: 9}); } else { str += string.charAt(i); } } return str; }; /** * parses string for symbols (numbers or letters) and replaces them appropriately (# will be replaced with number, * ? with letter and * will be replaced with number or letter) * * @method faker.helpers.replaceSymbols * @param {string} string */ self.replaceSymbols = function (string) { string = string || ""; var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] var str = ''; for (var i = 0; i < string.length; i++) { if (string.charAt(i) == "#") { str += faker.random.number(9); } else if (string.charAt(i) == "?") { str += faker.random.arrayElement(alpha); } else if (string.charAt(i) == "*") { str += faker.random.boolean() ? faker.random.arrayElement(alpha) : faker.random.number(9); } else { str += string.charAt(i); } } return str; }; /** * replace symbols in a credit card schems including Luhn checksum * * @method faker.helpers.replaceCreditCardSymbols * @param {string} string * @param {string} symbol */ self.replaceCreditCardSymbols = function(string, symbol) { // default values required for calling method without arguments string = string || "6453-####-####-####-###L"; symbol = symbol || "#"; // Function calculating the Luhn checksum of a number string var getCheckBit = function(number) { number.reverse(); number = number.map(function(num, index){ if (index%2 === 0) { num *= 2; if(num>9) { num -= 9; } } return num; }); var sum = number.reduce(function(prev,curr){return prev + curr;}); return sum % 10; }; string = faker.helpers.regexpStyleStringParse(string); // replace [4-9] with a random number in range etc... string = faker.helpers.replaceSymbolWithNumber(string, symbol); // replace ### with random numbers var numberList = string.replace(/\D/g,"").split("").map(function(num){return parseInt(num);}); var checkNum = getCheckBit(numberList); return string.replace("L",checkNum); }; /** string repeat helper, alternative to String.prototype.repeat.... See PR #382 * * @method faker.helpers.repeatString * @param {string} string * @param {number} num */ self.repeatString = function(string,num) { if(typeof num ==="undefined") { num = 0; } var text = ""; for(var i = 0; i < num; i++){ text += string.toString(); } return text; }; /** * parse string paterns in a similar way to RegExp * * e.g. "#{3}test[1-5]" -> "###test4" * * @method faker.helpers.regexpStyleStringParse * @param {string} string */ self.regexpStyleStringParse = function(string){ string = string || ""; // Deal with range repeat `{min,max}` var RANGE_REP_REG = /(.)\{(\d+)\,(\d+)\}/; var REP_REG = /(.)\{(\d+)\}/; var RANGE_REG = /\[(\d+)\-(\d+)\]/; var min, max, tmp, repetitions; var token = string.match(RANGE_REP_REG); while(token !== null){ min = parseInt(token[2]); max = parseInt(token[3]); // switch min and max if(min>max) { tmp = max; max = min; min = tmp; } repetitions = faker.random.number({min:min,max:max}); string = string.slice(0,token.index) + faker.helpers.repeatString(token[1], repetitions) + string.slice(token.index+token[0].length); token = string.match(RANGE_REP_REG); } // Deal with repeat `{num}` token = string.match(REP_REG); while(token !== null){ repetitions = parseInt(token[2]); string = string.slice(0,token.index)+ faker.helpers.repeatString(token[1], repetitions) + string.slice(token.index+token[0].length); token = string.match(REP_REG); } // Deal with range `[min-max]` (only works with numbers for now) //TODO: implement for letters e.g. [0-9a-zA-Z] etc. token = string.match(RANGE_REG); while(token !== null){ min = parseInt(token[1]); // This time we are not capturing the char befor `[]` max = parseInt(token[2]); // switch min and max if(min>max) { tmp = max; max = min; min = tmp; } string = string.slice(0,token.index) + faker.random.number({min:min, max:max}).toString() + string.slice(token.index+token[0].length); token = string.match(RANGE_REG); } return string; }; /** * takes an array and randomizes it in place then returns it * * uses the modern version of the Fisher–Yates algorithm * * @method faker.helpers.shuffle * @param {array} o */ self.shuffle = function (o) { if (typeof o === 'undefined' || o.length === 0) { return o || []; } o = o || ["a", "b", "c"]; for (var x, j, i = o.length - 1; i > 0; --i) { j = faker.random.number(i); x = o[i]; o[i] = o[j]; o[j] = x; } return o; }; /** * mustache * * @method faker.helpers.mustache * @param {string} str * @param {object} data */ self.mustache = function (str, data) { if (typeof str === 'undefined') { return ''; } for(var p in data) { var re = new RegExp('{{' + p + '}}', 'g') str = str.replace(re, data[p]); } return str; }; /** * createCard * * @method faker.helpers.createCard */ self.createCard = function () { return { "name": faker.name.findName(), "username": faker.internet.userName(), "email": faker.internet.email(), "address": { "streetA": faker.address.streetName(), "streetB": faker.address.streetAddress(), "streetC": faker.address.streetAddress(true), "streetD": faker.address.secondaryAddress(), "city": faker.address.city(), "state": faker.address.state(), "country": faker.address.country(), "zipcode": faker.address.zipCode(), "geo": { "lat": faker.address.latitude(), "lng": faker.address.longitude() } }, "phone": faker.phone.phoneNumber(), "website": faker.internet.domainName(), "company": { "name": faker.company.companyName(), "catchPhrase": faker.company.catchPhrase(), "bs": faker.company.bs() }, "posts": [ { "words": faker.lorem.words(), "sentence": faker.lorem.sentence(), "sentences": faker.lorem.sentences(), "paragraph": faker.lorem.paragraph() }, { "words": faker.lorem.words(), "sentence": faker.lorem.sentence(), "sentences": faker.lorem.sentences(), "paragraph": faker.lorem.paragraph() }, { "words": faker.lorem.words(), "sentence": faker.lorem.sentence(), "sentences": faker.lorem.sentences(), "paragraph": faker.lorem.paragraph() } ], "accountHistory": [faker.helpers.createTransaction(), faker.helpers.createTransaction(), faker.helpers.createTransaction()] }; }; /** * contextualCard * * @method faker.helpers.contextualCard */ self.contextualCard = function () { var name = faker.name.firstName(), userName = faker.internet.userName(name); return { "name": name, "username": userName, "avatar": faker.internet.avatar(), "email": faker.internet.email(userName), "dob": faker.date.past(50, new Date("Sat Sep 20 1992 21:35:02 GMT+0200 (CEST)")), "phone": faker.phone.phoneNumber(), "address": { "street": faker.address.streetName(true), "suite": faker.address.secondaryAddress(), "city": faker.address.city(), "zipcode": faker.address.zipCode(), "geo": { "lat": faker.address.latitude(), "lng": faker.address.longitude() } }, "website": faker.internet.domainName(), "company": { "name": faker.company.companyName(), "catchPhrase": faker.company.catchPhrase(), "bs": faker.company.bs() } }; }; /** * userCard * * @method faker.helpers.userCard */ self.userCard = function () { return { "name": faker.name.findName(), "username": faker.internet.userName(), "email": faker.internet.email(), "address": { "street": faker.address.streetName(true), "suite": faker.address.secondaryAddress(),