Git Product home page Git Product logo

casual's Introduction

Fake data generator Build Status

LOOKING FOR CONTRIBUTORS

#109

Installation

npm install casual

Usage

var casual = require('casual');

// Generate random sentence
// You don't need function call operator here
// because most of generators use properties mechanism
var sentence = casual.sentence;

// Generate random city name
var city = casual.city;

// Define custom generator
casual.define('point', function() {
	return {
		x: Math.random(),
		y: Math.random()
	};
});

// Generate random point
var point = casual.point;

// And so on..

Casual uses javascript properties for common generators so you don't need to use function call operator

Embedded generators

// Address

casual.country              // 'United Kingdom'
casual.city                 // 'New Ortiz chester'
casual.zip(digits = {5, 9}) // '26995-7979' (if no digits specified then random selection between ZIP and ZIP+4)
casual.street               // 'Jadyn Islands'
casual.address              // '6390 Tremblay Pines Suite 784'
casual.address1             // '8417 Veda Circles'
casual.address2             // 'Suite 648'
casual.state                // 'Michigan'
casual.state_abbr           // 'CO'
casual.latitude             // 90.0610
casual.longitude            // 180.0778
casual.building_number      // 2413

// Text

casual.sentence               // 'Laborum eius porro consequatur.'
casual.sentences(n = 3)       // 'Dolorum fuga nobis sit natus consequatur. Laboriosam sapiente. Natus quos ut.'
casual.title                  // 'Systematic nobis'
casual.text                   // 'Nemo tempore natus non accusamus eos placeat nesciunt. et fugit ut odio nisi dolore non ... (long text)'
casual.description            // 'Vel et rerum nostrum quia. Dolorum fuga nobis sit natus consequatur.'
casual.short_description      // 'Qui iste similique iusto.'
casual.string                 // 'saepe quia molestias voluptates et'
casual.word                   // 'voluptatem'
casual.words(n = 7)           // 'sed quis ut beatae id adipisci aut'
casual.array_of_words(n = 7)  // [ 'voluptas', 'atque', 'vitae', 'vel', 'dolor', 'saepe', 'ut' ]
casual.letter                 // 'k'

// Internet

casual.ip           // '21.44.122.149'
casual.domain       // 'darrion.us'
casual.url          // 'http://www.Germaine.net/'
casual.email        // '[email protected]'
casual.user_agent   // 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0'

// Person

casual.name            // 'Alberto'
casual.username        // 'Darryl'
casual.first_name      // 'Derek'
casual.last_name       // 'Considine'
casual.full_name       // 'Kadin Torphy'
casual.password        // '(205)580-1350Schumm'
casual.name_prefix     // 'Miss'
casual.name_suffix     // 'Jr.'
casual.company_name    // 'Cole, Wuckert and Strosin'
casual.company_suffix  // 'Inc'
casual.catch_phrase    // 'Synchronised optimal concept'
casual.phone           // '982-790-2592'

// Numbers

casual.random                            // 0.7171590146608651 (core generator)
casual.integer(from = -1000, to = 1000)  // 632
casual.double(from = -1000, to = 1000)   // -234.12987444
casual.array_of_digits(n = 7)            // [ 4, 8, 3, 1, 7, 6, 6 ]
casual.array_of_integers(n = 7)          // [ -105, -7, -532, -596, -430, -957, -234 ]
casual.array_of_doubles(n = 7)           // [ -866.3755785673857, -166.62194719538093, ...]
casual.coin_flip                         // true

// Date

casual.unix_time                    // 659897901
casual.moment                       // moment.js object see http://momentjs.com/docs/
casual.date(format = 'YYYY-MM-DD')  // '2001-07-06' (see available formatters http://momentjs.com/docs/#/parsing/string-format/)
casual.time(format = 'HH:mm:ss')    // '03:08:02' (see available formatters http://momentjs.com/docs/#/parsing/string-format/)
casual.century                      // 'IV'
casual.am_pm                        // 'am'
casual.day_of_year                  // 323
casual.day_of_month                 // 9
casual.day_of_week                  // 4
casual.month_number                 // 9
casual.month_name                   // 'March'
casual.year                         // 1990
casual.timezone                     // 'America/Miquelon'

// Payments

casual.card_type            // 'American Express'
casual.card_number(vendor)  // '4716506247152101' (if no vendor specified then random)
casual.card_exp             // '03/04'
casual.card_data            // { type: 'MasterCard', number: '5307558778577046', exp: '04/88', holder_name: 'Jaron Gibson' }

// Misc

casual.country_code    // 'ES'
casual.language_code   // 'ru'
casual.locale          // 'hi_IN'
casual.currency        // { symbol: 'R', name: 'South African Rand', symbol_native: 'R', decimal_digits: 2, rounding: 0, code: 'ZAR', name_plural: 'South African rand' }		
casual.currency_code   // 'TRY'
casual.currency_symbol // 'TL'
casual.currency_name   // Turkish Lira
casual.mime_type       // 'audio/mpeg'
casual.file_extension  // 'rtf'
casual.boolean         // true
casual.uuid            // '2f4dc6ba-bd25-4e66-b369-43a13e0cf150'

// Colors

casual.color_name       // 'DarkOliveGreen'
casual.safe_color_name  // 'maroon'
casual.rgb_hex          // '#2e4e1f'
casual.rgb_array        // [ 194, 193, 166 ]

Define custom generators

casual.define('user', function() {
	return {
		email: casual.email,
		firstname: casual.first_name,
		lastname: casual.last_name,
		password: casual.password
	};
});

// Generate object with randomly generated fields
var user = casual.user;

If you want to pass some params to your generator:

casual.define('profile', function(type) {
	return {
		title: casual.title,
		description: casual.description,
		type: type || 'private'
	};
});

// Generate object with random data
var profile = casual.profile('public');

NOTE: if getter function has non-empty arguments list then generator should be called as function casual.profile('public'), otherwise it should be accessed as property casual.profile.

Localization

You can get localized version of casual generator:

var casual = require('casual').ru_RU;
casual.street; // 'Бухарестская'

Default locale is en_US.

See src/providers/{{locale}} for more details about available locales and locale specific generators.

If you don't find necessary locale, please create an issue or just add it :)

Helpers

random_element

Get random array element

var item = casual.random_element(['ball', 'clock', 'table']);

random_value

Extract random object value

var val = casual.random_value({ a: 1, b: 3, c: 42 });
// val will be equal 1 or 3 or 42

random_key

Extract random object key

var val = casual.random_key({ a: 1, b: 3, c: 42 });
// val will be equal 'a' or 'b' or 'c'

populate

Replace placeholders with generators results

casual.populate('{{email}} {{first_name}}');
// '[email protected] Lyla'

populate_one_of

Pick random element from given array and populate it

var formats = ['{{first_name}}', '{{last_name}} {{city}}'];
casual.populate_one_of(formats);

// Same as

casual.populate(casual.random_element(formats));

numerify

Replace all # in string with digits

var format = '(##)-00-###-##';
casual.numerify(format); // '(10)-00-843-32'

define

See custom generators

register_provider

Register generators provider

var words = ['flexible', 'great', 'ok', 'good'];
var doge_provider = {
	such: function() {
		return 'such ' + casual.random_element(words);
	},

	doge_phrase: function() {
		return 'wow ' + casual.such();
	}
};

casual.register_provider(doge_provider);

casual.such;        // 'such good'
casual.doge_phrase; // 'wow such flexible'

Seeding

If you want to use a specific seed in order to get a repeatable random sequence:

casual.seed(123);

It uses Mersenne Twister pseudorandom number generator in core.

Generators functions

If you want to pass generator as a callback somewhere or just hate properties you always can access generator function at casual._{generator}

// Generate value using function
var title = casual._title();
// Same as
var title = casual.title;

// Pass generator as callback
var array_of = function(times, generator) {
	var result = [];

	for (var i = 0; i < times; ++i) {
		result.push(generator());
	}

	return result;
};

// Will generate array of five random timestamps
var array_of_timestamps = array_of(5, casual._unix_time);

Or you can get functional version of casual generator:

var casual = require('casual').functions();

// Generate title
casual.title();

// Generate timestamp
casual.unix_time();

View providers output cli

There is a simple cli util which could be used to view/debug providers output:

# Will render table with columns [generator_name, result] for all providers
node utils/show.js

 # Will render table with columns [generator_name, result] only for person provider
node utils/show.js person

Browserify support

Currently you can't use casual with browserify. Please check out this browserify-friendly fork Klowner/casual-browserify

Contributing

License

Heavily inspired by https://github.com/fzaninotto/Faker

The MIT License (MIT) Copyright (c) 2014 Egor Gumenyuk [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

casual's People

Contributors

a0viedo avatar adevade avatar alicelieutier avatar atlowell-smpl avatar bartholomej avatar boo1ean avatar britter avatar chamini2 avatar dmamills avatar domarmstrong avatar fleg avatar flesler avatar forabi avatar hanse avatar jplindgren avatar karbassi avatar lambrusco avatar leonistor avatar lil5 avatar ljharb avatar mlix8hoblc avatar msemenistyi avatar pearsonallen avatar rashkov avatar robertohuertasm avatar rohmanhm avatar simonratner avatar sskogen avatar tihomirivanov avatar tracer1337 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

casual's Issues

Error after a fresh install: 'exists` is not defined

After a fresh install, I get the following error:

WARNING in ./~/casual/src/casual.js
Critical dependencies:
6:9-26 the request of a dependency is an expression
 @ ./~/casual/src/casual.js 6:9-26

So I look at the code below in the source code:

var helpers = require('./helpers'),
    exists = require('fs').existsSync;

var safe_require = function(filename) {
    if (exists(filename + '.js')) {
        return require(filename);
    }
    return {};
};

and I think I should add fs package. After that, I still get the following error:

TypeError: exists is not a function

Browserify support

I would be nice to be able to use this module with browserify within the browser

How to define password in casual?

I need to generate a password with-
min length : 7
max length : 15
Uppercase : one letter atleast.
Lowercase : one letter atleast
Special charater : ~ ! @ # $ % ^ * ( ) _ + : ?

I used casual lib, but im unable to generate special character. Could any one help me on this issue?
var casual = require('casual');
var password = casual.password.substring(7,15);

Cannot be used with ESBuild

ESBuild does not run on node and thus doesn't use fs.

The issue is similar to #61

Instead of over-engineering locale requires why not have a list of all of them?

Random elements from array

What about adding a casual.random_element(array, x) to return x random elements from array?

Under the hood code could look like:

function getRandomArrayElements (array, count, startIndex, endIndex) {
  if (Array.isArray(array) === false) throw new Error('Invalid array object')
  if (startIndex < 0 || startIndex > array.length - 1) throw new Error('Invalid startIndex value')
  if (endIndex < 0 || endIndex > array.length - 1) throw new Error('Invalid endIndex value')
  if (count < startIndex || count > (endIndex - startIndex) + 1) throw new Error('Invalid count value')
  var resultList = []
  var temp, randomIndex
  while (count > 0) {
    randomIndex = chooseRandomNumer(startIndex, endIndex)
    temp = array[randomIndex]
    array[randomIndex] = array[endIndex]
    array[endIndex] = temp
    resultList.push(temp)
    count--
    endIndex--
  }
  return resultList
}

Just submitting the idea for validation, will come back with a PR if validated.

Custom Generator Types

I am relatively new to Typescript and I have been trying to read the most appropriate way to extend the current types available on Casual to accomodate custom generators. For example:

import * as casual from 'casual';

casual.define('stripeCard', (): CasualCard => {
	return {
		card: {
			number: '4242424242424242',
			exp_month: casual.integer(1, 12),
			exp_year: casual.integer(2019, 2020),
			cvc: casual.integer(100, 999),
		},
	};
});

But whatever I try does not seem to work?
Does anyone have experience extending the current index.d.ts?

Error: 'Exported external package typings is not a module' when using the module

Since TypeScript definitions were included in 1.5.4 I get the following error while compiling: "error TS2656: Exported external package typings file '.../node_modules/casual/index.d.ts' is not a module. Please contact the package author to update the package definition."

Before I used a trivial ambient definition which seemed to compile:

declare module 'casual' {
    const casual: any;

    export = casual;
}

Thanks!
Alberto

casual pollutes the global momentjs instance with Norwegian locale

Looks like when we import casual in our test framework it alters the global moment 's locale setting. All our modules under tests then decide to humanize dates in norwegian instead of english (the default). Should casual use "instance level" locale methods as described here: https://github.com/moment/momentjs.com/blob/master/docs/moment/06-i18n/02-instance-locale.md

I'm happy to submit a PR if someone can confirm this what should be done.. Looks like a small set of changes needed:
https://github.com/boo1ean/casual/search?utf8=%E2%9C%93&q=moment&type=

casual-moment

LOOKING FOR CONTRIBUTORS

Hi, currently I don't have time to contribute to this project.
I created this project 8 years ago and didn't refactor/improve code quality since, except for some contributions.
Looking for contributors who will take responsibility for development & refactoring.

Let me know in this thread if you are interested!
Thanks!

Feature request: Date in range

I would like to be able to generate a casual.unix_time that is between a certain range of dates.

Many thanks for a great module.

moment

Hey, can you guys clarifies that casual.moment is suppose to return moment functional object or moment().unix object. Thanks!

Typescript missing boolean definition

I am new of Typescript and would like using causal for helping generate fake data.

I notice that https://github.com/boo1ean/casual/blob/master/index.d.ts is missing definition of 'boolean' so that I can't invoke casual.boolean in typescript.

I have create monkey patch for fix that issue

`
import * as casual from "casual";

declare interface CasualMonkeyPatch {
boolean: boolean;
}
declare const casualPatch: casual & CasualMonkeyPatch;

export = casualPatch;
`

Hopefully it can merge into master branch index.d.ts .
Also it much much better register that in Typescript official definition repo

custom generators can break casual

Defining a custom generator with specific names can break other casual generators.

Example:

casual.define('letters', n => 'ABC');

// this built-in generator is now broken
casual.letter // => undefined

It only happens for me when custom generator named "letters" and it takes an argument.

Error when using casual with `create-react-app`

Steps to reproduce:

  1. Create a new React app using create-react-app, i.e. npm create react-app casual-test
  2. Run yarn add casual
  3. Update the default App.js component like this
  4. Run yarn start

The browser opens automatically and shows an error page saying TypeError: exists is not a function, pointing to this line

Tested on macOs Mojave (10.14.3) and Windows 10 1803

A quick SO search revealed this similar issue (Webpack...).

Typescript declarations are outdated

For example, everything related to currency is missing in the index.d.ts file.

Docs

// Misc

casual.country_code    // 'ES'
casual.language_code   // 'ru'
casual.locale          // 'hi_IN'
casual.currency        // { symbol: 'R', name: 'South African Rand', symbol_native: 'R', decimal_digits: 2, rounding: 0, code: 'ZAR', name_plural: 'South African rand' }		
casual.currency_code   // 'TRY'
casual.currency_symbol // 'TL'
casual.currency_name   // Turkish Lira
casual.mime_type       // 'audio/mpeg'
casual.file_extension  // 'rtf'
casual.boolean         // true
casual.uuid            // '2f4dc6ba-bd25-4e66-b369-43a13e0cf150'

index.d.ts

    // Misc

    country_code: string;     // 'ES'
    language_code: string;    // 'ru'
    locale: string;           // 'hi_IN'
    mime_type: string;        // 'audio/mpeg'
    file_extension: string;   // 'rtf'
    uuid: string;             // '2f4dc6ba-bd25-4e66-b369-43a13e0cf150'

integer generator is noticeably biased away from the ends of the range

The casual.integer generator is noticeably biased away from the ends of the range; the start and end of the range only occur with half the frequency of the other elements.

The reason for this is the use of Math.round and a range of to-from, which is not big enough. A better formula might be:

Math.floor(from + (to - from + 1) * this.random)

Of course, this would break anyone who is depending on the same answers with the same seed, so maybe a new method would be better?

Company Names are Rather Limited

Company names (English default locale) are rather limited, and end up leading to many repeats with a relatively small amount of data (1700 company names).

Support for React Native

React Native doesn't run in Node.js environment (see StackOverflow), therefore requiring the 'fs' module causes an error. Furthermore, it seems React Native doesn't support programmatic require (called in a loop over an array of providers). I was able to fix this by replacing the for loop with individual statements without using the safe_require function which uses 'fs', unfortunately with a fixed en_US locale, e.g.:

casual.register_provider(helpers.extend(
	require('./providers/address'),
	require('./providers/en_US/address')
));
casual.register_provider(helpers.extend(
	require('./providers/text'),
	{}
));

Changing password generator

Perhaps the password generator should return a hexadecimal password of length n thats declared by the user.

For example:

    casual.password(8)   // c8b72fa

Currency support

Is there currency support available (I couldn't find it). If not, probably it's worth implementing

phone numbers not valid

phone_formats: ['###-###-####'],

this format is not really valid, needs to be

['200-200-0000']
where:
0 replaced by 0-9
2 replaced by 2-9

otherwise the number generated is not valid the first number in the area code and the prefix cannot be 0 or 1 (ie the ones replaced with 2s above)

Create a standalone, static build?

Is it possible to create a standalone build for use as a vanilla .js script include in the browser?
I want to create a mockup for my current project, but don't want to fuss with Node - I just want to be able to include it in a .html page and go...

Including library into CasperJs

I tried using library by just including it as require('casual')

I get the following error in response:

6300111528b901b9630b9115_28-01-2016-23 53 55_b901

I tried to look for meaning of __dirname but didn't find where it was defined.

What am I doing wrong?

Dynamic require with `safe_require` prints a warning in Webpack 5

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/casual/src/casual.js b/node_modules/casual/src/casual.js
index 9179af1..0706dca 100644
--- a/node_modules/casual/src/casual.js
+++ b/node_modules/casual/src/casual.js
@@ -1,12 +1,6 @@
 var helpers = require('./helpers');
 var exists = require('fs').existsSync;
-
-var safe_require = function(filename) {
-	if (exists(filename + '.js')) {
-		return require(filename);
-	}
-	return {};
-};
+var path = require('path');
 
 var build_casual = function() {
 	var casual = helpers.extend({}, helpers);
@@ -40,9 +34,16 @@ var build_casual = function() {
 			var casual = build_casual();
 
 			providers.forEach(function(provider) {
+				let localeProvider = {};
+				try {
+					localeProvider = require(__dirname + '/providers/' + locale + '/' + provider)
+				} catch (e) {
+					// Nothing to do
+				}
+
 				casual.register_provider(helpers.extend(
 					require('./providers/' + provider),
-					safe_require(__dirname + '/providers/' + locale + '/' + provider)
+					localeProvider
 				));
 			});
 

This issue body was partially generated by patch-package.

Invalid Cardtype Leads to Crash for card_number()

Specifying an invalid card type (such as "visa" rather than "Visa") causes a crash. This is due to the statement on line 41 of payment.js not correctly checking for invalid parameters:

var mask = this.random_element(this.card_params[vendor]);

House number may contain chars

I believe, that in many countries house number may contain dashes, alphas, slashes or some other symbols. I think, it's worth amending as this may sometimes be key point in validating system coping with house numbers.

Use TS generics to improve random_element return type

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Some of the functions could easily have their TS types improved by using generics.

Here is the diff that solved my problem:

diff --git a/node_modules/casual/index.d.ts b/node_modules/casual/index.d.ts
index b556860..b0098e5 100644
--- a/node_modules/casual/index.d.ts
+++ b/node_modules/casual/index.d.ts
@@ -282,7 +282,7 @@ declare namespace Casual {
     define(type: string, cb: (...args: any[]) => any): void;
 
     // HELPERS
-    random_element(elements: Array<any>): any;
+    random_element<T>(elements: Array<T>): T;
     random_value(obj: Object): any;
     random_key(obj: Object): any;
     populate(str: string): string;

This issue body was partially generated by patch-package.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.