0.0.2 • Published 7 years ago
random-function v0.0.2
random-function
Create a function that when executed, calls a function randomly based on a given weighted array of functions.
Installation
npm install -S random-function
Usage
import randomFunction from 'random-function';
// --- DEMO 1: create a "balancedGreet()" function
const balancedGreet = randomFunction([
{ weight: 100, fn: name => `Hello ${name}` },
{ weight: 100, fn: name => `Have a nice day ${name}` },
{ weight: 100, fn: name => `Wassup ${name}`},
name => `Hi ${name}`, // just specify a function as a shorthand (weight auto-set to 100)
]);
// each of the 4 greeting functions has an equal chance of being called each time
// balancedGreet() is called
balancedGreet('Bob');
// --- DEMO 2: create a "weightedGreet()" function
const weightedGreet = randomFunction([
{ weight: 50, fn: name => `Hello ${name}` },
{ weight: 25, fn: name => `Have a nice day ${name}` },
{ weight: 25, fn: name => `Wassup ${name}`},
]);
// "Hello" has 50% chance of being called, while the other 2 functions has 25% each
weightedGreet('Bob');
Test Coverage
Test coverage report.
History
v0.0.1 (29 Dec 2016) - First version.