Skip to content

Commit

Permalink
new text method and rework of building process
Browse files Browse the repository at this point in the history
* Add new text function. It generates large text, separated with spaces
* Rework str function. Now it can produce uppercase, lowercase and
capitalized strings
* Add global random function, so it can be replaced with custom one
* Add webpack build system, now library can be used in web via script
  tag
* Bump version
  • Loading branch information
PunGy committed May 3, 2022
1 parent 4b49426 commit 804304e
Show file tree
Hide file tree
Showing 28 changed files with 1,176 additions and 147 deletions.
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/dist
/module
/scripts
*.config.js
*.config.ts
4 changes: 2 additions & 2 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
node: [ '10', '12', '14', '15' ]
os: [ubuntu-latest]
node: [ '12', '14', '15' ]
steps:
- uses: actions/checkout@v2
- name: Setup Node
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ typings/
# Nuxt.js build / generate output
.nuxt
dist
types

# Gatsby files
.cache/
Expand All @@ -105,3 +106,6 @@ dist

# TernJS port file
.tern-port

# Mac local files
.DS_Store
1 change: 0 additions & 1 deletion jest.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
},
"preset": "ts-jest",
"testEnvironment": "node",
"collectCoverage": true,
"collectCoverageFrom": [
"src/**/*.ts"
],
Expand Down
20 changes: 14 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mockaroni",
"version": "0.3.1",
"version": "0.4.0",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"author": "Maxim Yakovlev <max.yakovlev555@gmail.com>",
Expand All @@ -19,17 +19,21 @@
],
"files": [
"dist/**/*",
"types/**/*",
"package.json",
"README.md",
"LICENSE"
],
"scripts": {
"test": "jest",
"test": "jest --maxWorkers=50%",
"test:ci": "jest --runInBand",
"test:coverage": "jest --coverage",
"test:dev": "jest --watchAll",
"lint": "eslint \"**/*.{js,ts}\"",
"test:dev": "jest --watch --maxWorkers=25%",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
"type-check": "tsc --project tsconfig.production.json --noEmit",
"build": "tsc --project tsconfig.production.json",
"build": "yarn run build:code && yarn run build:types",
"build:code": "webpack-cli",
"build:types": "tsc --project tsconfig.typegen.json && rm -rf ./temp",
"postinstall": "husky install",
"prepublishOnly": "pinst --disable",
"postpublish": "pinst --enable"
Expand All @@ -48,7 +52,11 @@
"pinst": "^2.1.4",
"prettier": "^2.2.1",
"ts-jest": "^26.5.1",
"typescript": "^4.1.5"
"ts-loader": "^9.3.0",
"typedoc": "^0.22.15",
"typescript": "^4.1.5",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2"
},
"engines": {
"node": ">= 8.0.0"
Expand Down
14 changes: 14 additions & 0 deletions src/globalConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export type MockaroniConfig = {
/**
* Randomization function
*/
random: () => number;
}
export const globalConfig = {
random: Math.random,
}

export const setConfig = (nextConfig: MockaroniConfig) =>
{
Object.assign(globalConfig, nextConfig)
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './primitives/boolean'
export * from './primitives/oneOf'
export * from './primitives/num'
export * from './primitives/str'
Expand All @@ -8,3 +9,4 @@ export * from './lists/replicate'
export * from './lists/listOf'

export * from './utils'
export { MockaroniConfig, setConfig } from './globalConfig'
10 changes: 9 additions & 1 deletion src/lists/listOf.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { Config, trueOrFalse } from '../utils'
import { Config } from '../utils'
import { oneOf } from '../primitives/oneOf'
import { trueOrFalse } from '../primitives/boolean'

/**
* Generates an array of provided values from list param
* @param config {Object}
* @param config.size - the size of resulting array
* @param config.list - list of values which resulting array will contain
* @param config.nullable - result can be null
*/
export const listOf = <T>(config: Config<{ size: number; list: Array<T>; }>): Array<T> =>
{
if (config.nullable) if (trueOrFalse()) return null
Expand Down
19 changes: 16 additions & 3 deletions src/lists/range.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
import { Config, trueOrFalse } from '../utils'
import { Config } from '../utils'
import { trueOrFalse } from '../primitives/boolean'

export const range = (config: Config<{ from: number; to: number; }>): Array<number> =>
export type RangeConfig = { from: number; to: number; }

export function range(listOf: number): Array<number>;
export function range(config: Config<RangeConfig>): Array<number>
/**
* Generates a range of integers
* @param config {Object} Could be a config object, or number (in this case, config object would be { from: 0, to: number })
* @param config.from - start point of numbers in the range
* @param config.to - end point of numbers in the range
* @param config.nullable - result can be null
*/
export function range (config: Config<RangeConfig> | number): Array<number>
{
if (typeof config === 'number') config = { from: 0, to: config }
if (config.nullable) if (trueOrFalse()) return null

return Array.from(
Array(config.to - config.from),
(_, i) => config.from + i,
(_, i) => (config as RangeConfig).from + i,
)
}
10 changes: 9 additions & 1 deletion src/lists/replicate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { Config, trueOrFalse } from '../utils'
import { Config } from '../utils'
import { trueOrFalse } from '../primitives/boolean'

/**
* Generates an array of values from schema (like a second parameter of Array.from)
* @param config {Object}
* @param config.size - the size of resulting array
* @param config.schema - map function
* @param config.nullable - result can be null
*/
export const replicate = <R>(config: Config<{ size: number; schema: (index: number) => R; }>): Array<R> =>
{
if (config.nullable) if (trueOrFalse()) return null
Expand Down
6 changes: 6 additions & 0 deletions src/primitives/boolean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { globalConfig } from '../globalConfig'

/**
* Returns true or false
*/
export const trueOrFalse = () => Boolean(Math.round(globalConfig.random()))
12 changes: 10 additions & 2 deletions src/primitives/date.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { Config, trueOrFalse } from '../utils'
import { num } from '../primitives/num'
import { Config } from '../utils'
import { num } from './num'
import { trueOrFalse } from './boolean'

/**
* Generates a random date
* @param config {Object}
* @param config.min - start point of date
* @param config.max - end point of date
* @param config.nullable - result can be null
*/
export const date = (config: Config<{ min: Date; max: Date; }>): Date =>
{
if (config.nullable) if (trueOrFalse()) return null
Expand Down
11 changes: 10 additions & 1 deletion src/primitives/num.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { Config, trueOrFalse } from '../utils'
import { Config } from '../utils'
import { trueOrFalse } from './boolean'

/**
* Generates a random number
* @param config {Object}
* @param config.min - low border of numbers
* @param config.max - high border of numbers
* @param config.type - would a result number be an integer or float
* @param config.nullable - result can be null
*/
export const num = (config: Config<{ min: number; max: number; type?: 'float'|'int'; }>) =>
{
if (config.nullable)
Expand Down
13 changes: 10 additions & 3 deletions src/primitives/oneOf.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { Config, trueOrFalse } from '../utils'
import { num } from '../primitives/num'
import { Config } from '../utils'
import { num } from './num'
import { trueOrFalse } from './boolean'

export const oneOf = <T>(config: Config<{ list: Array<T>; }>): T =>
/**
* Providing a value from the list
* @param config {Object}
* @param config.list - list of values
* @param config.nullable - result can be null
*/
export const oneOf = <T>(config: Config<{ list: ArrayLike<T>; }>): T =>
{
if (config.nullable)
if (trueOrFalse()) return null
Expand Down
69 changes: 46 additions & 23 deletions src/primitives/str.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,60 @@
import { num } from '../index'
import { Config, trueOrFalse } from '../utils'
import { oneOf } from './oneOf'
import { Config } from '../utils'
import { trueOrFalse } from './boolean'

const alphabets = {
en: {
capitalized: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
normal: 'abcdefghijklmnopqrstuvwxyz',
latin: {
uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
lowercase: 'abcdefghijklmnopqrstuvwxyz',
get capitalized()
{
return this.lowercase
},
get mixed()
{
return this.normal + this.capitalized
return this.lowercase + this.uppercase
},
},
ru: {
capitalized: 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ',
normal: 'абвгдеёжзийклмнопрстуфхцчшщэюя',
cyrillic: {
uppercase: 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ',
lowercase: 'абвгдеёжзийклмнопрстуфхцчшщэюя',
get capitalized()
{
return this.lowercase
},
get mixed()
{
return this.normal + this.capitalized
return this.lowercase + this.uppercase
},
},
numbers: '000111222333444555666777888999', // duplicate number to be relativity compatible by size with language alphabets
/**
* Since in alphanumeric type we are using both alphabet and number
* We need to duplicate numbers to be relativity compatible by size with language alphabets
*/
numbers: '000111222333444555666777888999',
}
export const str = (config: Config<{

export type StringConfig = {
type?: 'alpha'|'numeric'|'alphanumeric';
locale?: 'ru'|'en';
format?: 'capitalized'|'normal'|'mixed';
size: {
min: number;
max: number;
} | number;
}>): string | null =>
locale?: 'cyrillic'|'latin';
format?: 'capitalized'|'lowercase'|'uppercase'|'mixed';
size: number;
}
/**
* Generates a random string
* @param config {Object}
* @param config.size - the size of resulting string
* @param config.type - which characters would be in a string
* @param config.locale - alphabet of a string
* @param config.format - case of string
* @param config.nullable - result can be null
*/
export const str = (config: Config<StringConfig>): string | null =>
{
if (config.nullable) if (trueOrFalse()) return null
config.locale = config.locale ?? 'en'
config.format = config.format ?? 'normal'
config.locale ??= 'latin'
config.format ??= 'lowercase'
config.type ??= 'alpha'

let result = ''
const alphabet = config.type === 'numeric'
Expand All @@ -41,10 +63,11 @@ export const str = (config: Config<{
? alphabets[config.locale][config.format]
: alphabets[config.locale][config.format] + alphabets.numbers

const length = typeof config.size === 'number' ? config.size : num(config.size)
const length = config.size
for ( let i = 0; i < length; i++ )
{
result += alphabet.charAt(Math.floor(Math.random() * alphabet.length))
result += oneOf({ list: alphabet })
if (config.format === 'capitalized' && i === 0) result = result.toUpperCase()
}
return result
}
71 changes: 71 additions & 0 deletions src/primitives/text.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { assignSoft, capitalize, Config } from '../utils'
import { str, StringConfig } from './str'
import { oneOf } from './oneOf'
import { replicate } from '../lists/replicate'

export type PartialWordsSet = {
words?: Array<string>;
names?: {
male?: Array<string>;
female?: Array<string>;
mixed?: Array<string>;
};
}

// eslint-disable-next-line max-len
const femaleNames = ['Rebecca', 'Mariam', 'Kimberly', 'Samantha', 'Taylor', 'Annie', 'Evie', 'Ayesha', 'Lola', 'Tiffany', 'Flora', 'Mia', 'Yasmin', 'Erica', 'Amina', 'Leona', 'Nia', 'Miriam', 'Jay', 'Hayley', 'Michelle', 'Daisy', 'Megan', 'Eva', 'Iqra', 'Jerry', 'Alfie', 'Bailey', 'Kelly', 'Mabel', 'Nellie', 'Kyra', 'Katy', 'Kira', 'Deborah', 'Zahra', 'Rowan', 'Rachel', 'Ebony', 'Michaela', 'Thea', 'Gracie', 'Willie', 'Melanie', 'Hattie', 'Rita', 'Sofia', 'Cory', 'Paula', 'Nancy', 'Evangeline', 'Anisa', 'Lana', 'Savannah', 'Tilly', 'Jacqueline', 'Susan', 'Lachlan', 'Monica', 'Amy', 'Aminah', 'Mason', 'Hazel', 'Rosa', 'Claudia', 'Vanessa', 'Melissa', 'Isobel', 'Anita', 'Jennifer', 'Ellis', 'Eliza', 'Spencer', 'Haleema', 'Jamie', 'Alisha', 'Darcie', 'Tanisha', 'Maryam', 'Isla', 'Connie', 'Phoebe', 'Sophie', 'Kiera', 'Katie', 'Cara', 'Sarah', 'Harley', 'Laura', 'Kaitlyn', 'Tina', 'Teresa', 'Faith', 'Alesha', 'Lara', 'Sadie', 'Anne', 'Tamara', 'Tia', 'Lucie']
// eslint-disable-next-line max-len
const maleNames = ['Glenn', 'Xavier', 'Musa', 'Darren', 'Ryan', 'Evangeline', 'Christian', 'Otis', 'Sienna', 'Tyler', 'Xander', 'Aadam', 'Julian', 'Hamzah', 'Farhan', 'Niall', 'Owain', 'Jamie', 'Elmer', 'Oliver', 'Isaac', 'Kyle', 'Myles', 'Hashim', 'Jerry', 'Leroy', 'Jakob', 'Jeffrey', 'Imran', 'Ted', 'Emmanuel', 'Patrick', 'Ajay', 'Juan', 'Sara', 'Rebekah', 'Jose', 'Connor', 'Justin', 'Richard', 'Herman', 'Renee', 'Nicholas', 'Solomon', 'Dale', 'Kye', 'Anas', 'Louis', 'Josh', 'Fabian', 'Kevin', 'Dewey', 'Anika', 'Ross', 'Willard', 'Sean', 'Caleb', 'Muhammad', 'Melvin', 'Ernest', 'Ruben', 'David', 'Jenna', 'Elena', 'Spencer', 'Ronald', 'Todd', 'Courtney', 'Guy', 'Tony', 'Reuben', 'Ethan', 'Aidan', 'Jake', 'Jessie', 'Lachlan', 'Charley', 'Casey', 'Will', 'Leonard', 'Zac', 'Harold', 'Stanley', 'Marcel', 'Mark', 'Mustafa', 'Carl', 'Amir', 'Amaan', 'Terry', 'Howard', 'Edgar', 'Victor', 'Sana', 'Sam', 'Adrian', 'Ronan', 'Phillip', 'Abby', 'Kira']
export const wordsSet = {
// eslint-disable-next-line max-len
words: ['spade', 'thunder', 'zany', 'broad', 'hissing', 'poor', 'veil', 'sidewalk', 'milk', 'mellow', 'circle', 'tangible', 'sea', 'grin', 'actually', 'holistic', 'peaceful', 'carve', 'wine', 'reflective', 'cowardly', 'event', 'advise', 'butter', 'clever', 'visit', 'scold', 'volleyball', 'rhythm', 'agonizing', 'magic', 'mouth', 'dapper', 'rat', 'slap', 'jumpy', 'upbeat', 'flat', 'determined', 'sordid', 'whine', 'abandoned', 'morning', 'relax', 'huge', 'frog', 'call', 'blue-eyed', 'squirrel', 'balance', 'giants', 'eatable', 'careful', 'troubled', 'record', 'word', 'hushed', 'clear', 'straight', 'comfortable', 'enormous', 'offer', 'protect', 'double', 'unnatural', 'lamp', 'wry', 'false', 'smash', 'fixed', 'whimsical', 'comb', 'cute', 'eye', 'faithful', 'kittens', 'shame', 'crayon', 'astonishing', 'tow', 'education', 'capable', 'deep', 'filthy', 'fire', 'symptomatic', 'waggish', 'perpetual', 'accurate', 'reject', 'naive', 'parcel', 'absurd', 'ducks', 'selfish', 'hot', 'oceanic', 'dynamic', 'knowing', 'stupid', 'flesh', 'vacation', 'clam', 'fantastic', 'liquid', 'cannon', 'potato', 'shivering', 'numerous', 'earn', 'glow', 'nest', 'rotten', 'army', 'cumbersome', 'clip', 'guide', 'meaty', 'jam', 'woozy', 'bag', 'scarce', 'metal', 'mundane', 'raise', 'boiling', 'complex', 'engine', 'floor', 'toothsome', 'muddle', 'descriptive', 'cooing', 'fumbling', 'race', 'good', 'barbarous', 'color', 'knowledge', 'theory', 'chubby', 'fence', 'sister', 'adorable', 'bedroom', 'nostalgic', 'rich', 'detect', 'cow', 'cycle', 'unbecoming', 'grass', 'time', 'cry', 'rapid', 'thing', 'lumber', 'guttural', 'reduce', 'exist', 'adhesive', 'language', 'hellish', 'groovy', 'well-to-do', 'women', 'scrawny', 'war', 'sun', 'strange', 'zippy', 'eyes', 'meal', 'wonderful', 'cable', 'oranges', 'evanescent', 'craven', 'obtainable', 'flavor', 'sleep', 'flagrant', 'warm', 'brake', 'extra-large', 'general', 'frightened', 'permissible', 'standing', 'touch', 'system', 'frail', 'agreement', 'school', 'back', 'stain', 'smile', 'cheap', 'direful', 'voice', 'sheep', 'equable', 'violet', 'numberless', 'tumble', 'truculent', 'limit', 'tempt', 'tall', 'carry', 'jagged', 'arm', 'omniscient', 'better', 'subdued', 'thumb', 'hard-to-find', 'learned', 'earthy', 'badge', 'early', 'difficult', 'mint', 'abaft', 'lewd', 'yummy', 'capricious', 'melodic', 'tacit', 'seemly', 'ruddy', 'identify', 'income', 'neighborly', 'gate', 'shape', 'coordinated', 'mammoth', 'taboo', 'doctor', 'intelligent', 'legs', 'curious', 'shut', 'iron', 'boy', 'cows', 'puny', 'moan', 'valuable'],
names: {
male: maleNames,
female: femaleNames,
mixed: maleNames.concat(femaleNames),
},
}

/**
* Generates a random text separated by spaces
* @param config {Object}
* @param config.wordsCount - count of words in resulting text
* @param config.type - the content of resulting text, would it be a random strings, names or plain words
* @param config.randomStringConfig - config of random string if the type is 'random_string'
* @param config.namesGender - genders of names if the type is 'names'
* @param config.capitalized - should the text be capitalized (first letter is in upper case)
* @param config.wordsSet - custom list of words and names
* @param config.nullable - result can be null
*/
export const text = (config: Config<{
type?: 'words'|'random_string'|'names';
namesGender?: 'male'|'female'|'mixed';
randomStringConfig?: StringConfig;
wordsSet?: PartialWordsSet;
capitalized?: boolean;
wordsCount: number;
}>): string =>
{
config.type ??= 'words'
config.namesGender ??= 'mixed'
config.randomStringConfig ??= { size: 5 }
config.capitalized ??= false
config.wordsSet = assignSoft(config.wordsSet ?? {}, wordsSet)

const wordSet = config.type === 'random_string'
? [] as Array<string> // we will not use it in this case
: config.type === 'words'
? wordsSet[config.type]
: wordsSet[config.type][config.namesGender]

const generateWord = config.type === 'random_string'
? () => str(config.randomStringConfig)
: () => oneOf({ list: wordSet })

const result = replicate({
size: config.wordsCount,
schema: generateWord,
}).join(' ')

return config.capitalized ? capitalize(result) : result
}
Loading

0 comments on commit 804304e

Please sign in to comment.