Giter VIP home page Giter VIP logo

better-randstr's Introduction

better-randstr

Build Status npm version

🌞 Fully-customizable random string generator. Useful for testing applications, etc.

  • Works with browsers, NodeJS and DenoJS (JavaScript 6+ and TypeScript)
  • No external dependencies
  • Unit-tested
  • Semantic Versioning
  • It can be used with your preferred pseudo-random generator (PRNG).

Install

npm i better-randstr

Declaration

Browser

Global:

<script crossorigin src="https://unpkg.com/better-randstr" >
<script>console.log( randstr() );</script>

ESM:

<script type="module" >
import { randstr } from 'https://unpkg.com/better-randstr/index.esm.js';
console.log( randstr() );
</script>

NodeJS

const { randstr } = require('better-randstr');
console.log( randstr() );

Deno

import { randstr } from 'https://unpkg.com/better-randstr/index.esm.js';
console.log( randstr() );

Usage Examples

// Default:
// - Up to 100 characters
// - No control characters
// - ASCII + ISO (UTF-8)
randstr();
// => ;Þë?Ç¡m{îU4I0_%L*qV

// Using a customized function as random function, instead of Math.random()
const myRandomFunc = /* a function that returns a number between 0 and 1 */ ;
randstr( { random: myRandomFunc } );
// => cy¦¼Óé6Lcy

// Exactly 10 characters
randstr( { length: 10 } );
// => »²y+iÀëC#Ù

// At least 10 characters
randstr( { length: [ 10 ] } );
// => ü¢ ß~å¿Û¿\ÓÜtÈ["ª9¡.:`i¡{ã«?®Q=>?v&ëÿ2"Âë

// At most 10 characters
randstr( { length: [ 0, 10 ] } );
// => ȹt×úÓ¯ÖÃj

// Between 2 and 60 characters
randstr( { length: [ 2, 60 ] } );
// => ZÔý­ÛÏaæ»û_Eâo9¨§­:Çu!ÕÄø|FNߨj)1n¦Í:

// Exactly 10 characters, with only the specified characters
randstr( { length: 10, chars: 'ABC123' } );
// => A31AAB3AB1

// Exactly 10 characters, only characters in the range, no control characters
randstr( { length: 10, chars: [ 32, 127 ] } ); // ASCII range
// => EA*bY7{*cL

// Exactly 10 characters, between 'A' and 'Z'
randstr( { length: 10, chars: [ 'A'.charCodeAt( 0 ), 'Z'.charCodeAt( 0 ) ] } );
// => SPQJNORXXR

// Exactly 10 characters, only numbers
const NUMBERS = require( 'better-randstr' ).NUMBERS;
randstr( { length: 10, chars: NUMBERS } ) // same as passing '0123456789'
// => 7450625283

// Exactly 10 characters, alfanumeric
const ALPHA_NUMERIC = require( 'better-randstr' ).ALPHA_NUMERIC;
randstr( { length: 10, chars: ALPHA_NUMERIC } );
// => s1wMa7QVmg

// Exactly 10 characters, all characters in ASCII/ISO (UTF-8) except the specified
randstr( { length: 10, acceptable: function( chr ) {
    return '%#&$'.indexOf( chr ) < 0; // acceptable if not found
} } );
// => ´NvÄ~]¿Gº]

// Exactly 10 characters, escaping quotes and single-quotes
randstr( { length: 10, replacer: function( chr ) {
    switch ( chr ) {
        case '"': return '\\"';
        case "'": return "\\'";
    }
    return chr;
} } );
// => ñ;}éÔÝf«\'

// Include control characters
randstr( { includeControlChars: true } );
// => x@HA$÷°Gݳ:^Ê%¼�¤®ý±�#Sh�+�Ò+Å|

// Wider range than UTF-8 - control characters not avoided!
randstr( { chars: [ 32, 1000 ] } );
// => r΅4ƹǭ̻ɍĿΠsɊQȍάĠIJȤċƳȭɧĄƹĜʋ͏Ʒȥĭ˟͢"Ȓǭ̼Ζ˂̀ƖǛ̚3&΃ƏϧȷɥŃ

See example.js

API

function randstr( options: Options ): string;

where Options is :

{

    /**
     * Random function to be used. By default, it assumes `Math.random()`.
     *
     * The function does not expect arguments and must return a number between 0 and 1.
     */
    random?: function () => number;

    /**
     * Length or length range. By default, it assumes `[ 0, 100 ]`.
     *
     * - Number: Minimum and maximum length will be equal to the provided number. Example: `{ length: 20 }`.
     * - One-length array: Maximum will be a random number greater than or equal to the minimum. Example: `{ length: [ 2 ] }`.
     * - Two-length array: Minimum and maximum length will assume the provided numbers. Example: `{ length: [ 0, 50 ] }`.
     */
    length?: number | number[];

    /**
     * Allowed characters or byte range. By default, it assumes `[32, 255]`
     * which is a range containing the first printable ASCII character (`32`)
     * and the last ISO character (`255`).
     *
     * For example, `"0123456789"`, which gives the same result as
     * `['0'.charCodeAt(0), '9'.charCodeAt(0)]`.
     */
    chars?: string | number[];

    /**
     * Function that evaluates whether the generated character is acceptable.
     * By default, it is `undefined`.
     * The function expects a character and returns a boolean.
     */
    acceptable?: function ( string ) => boolean;

    /**
     * Function that replaces a character by other character or characters.
     * By default, it is `undefined`.
     * You may use it for escaping or replacing certain characters, for example.
     */
    replacer?: function ( string ) => string;

    /**
     * Whether is desired to include control characters. By default, it is `false`.
     */
    includeControlChars?: boolean;
}

See also

License

MIT © Thiago Delgado Pinto

better-randstr's People

Contributors

thiagodp avatar

Stargazers

 avatar

Watchers

 avatar  avatar

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.