Socket
Socket
Sign inDemoInstall

random-words

Package Overview
Dependencies
Maintainers
11
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

random-words - npm Package Compare versions

Comparing version 1.3.0 to 2.0.0

27

CHANGELOG.md
# Changelog
## 2.0.0 - 2023-06-08
This is a significant update that transforms this module into an ECMAScript module and changes the name of the exported function. For that reason, we have updated the major version number.
- Converted default export to named export (`generate`) to generate random words.
- Adds `count` named export to count number of words.
- Thanks to [prateek-budhiraja](https://github.com/prateek-budhiraja) for these updates.
- Addition of `minLength` option.
- Code update to ES6 Syntax.
- Thanks to [Nellfs](https://github.com/nellfs) for these updates.
## 1.3.0 - 2023-02-17
* Adds new `seed` option. Thanks to [Nathan Klingensmith](https://github.com/IamParadoxdotexe).
- Adds new `seed` option. Thanks to [Nathan Klingensmith](https://github.com/IamParadoxdotexe).
## 1.2.1 - 2023-01-06
* Fixes misspelling of `separator` in typings. Thanks to Andrei Gec for the correction.
- Fixes misspelling of `separator` in typings. Thanks to Andrei Gec for the correction.
## 1.2.0 - 2022-06-16
* Adds typescript typings. Thanks to Tim Kennedy for this contribution.
- Adds typescript typings. Thanks to Tim Kennedy for this contribution.
## 1.1.2 - 2022-01-20
* Updates mocha to v9.
- Updates mocha to v9.
## 1.1.1
* Use `var` in a small amount of newer code that used `let`, to match ES5 legacy support status of the rest of the module. We should probably decide on a strategy for moving this module to ES6, but there is no urgency.
- Use `var` in a small amount of newer code that used `let`, to match ES5 legacy support status of the rest of the module. We should probably decide on a strategy for moving this module to ES6, but there is no urgency.
## 1.1.0
* Addition of `wordsPerString`, `separator` and `format` options. Thanks to Matteo Veraldi.
- Addition of `wordsPerString`, `separator` and `format` options. Thanks to Matteo Veraldi.
## 1.0.0
* Addition of `maxLength` option, thanks to Scoombe.
- Addition of `maxLength` option, thanks to Scoombe.
* Since this module has achieved considerable use, has good test coverage and has had no bug reports, we've declared version 1.0.0 stable. We will follow the semver standard from here on out.
- Since this module has achieved considerable use, has good test coverage and has had no bug reports, we've declared version 1.0.0 stable. We will follow the semver standard from here on out.

@@ -33,0 +44,0 @@ ## 0.0.1

@@ -1,5 +0,6 @@

declare type WordsOptions = {
declare type GenerateOptions = {
min?: number;
max?: number;
exactly?: number;
minLength?: number;
maxLength?: number;

@@ -12,9 +13,17 @@ wordsPerString?: number;

declare type JoinedWordsOptions = WordsOptions & { join: string; };
declare type JoinedWordsOptions = GenerateOptions & { join: string };
declare function words(count: number): string[];
declare function words(options: WordsOptions): string[];
declare function words(options: JoinedWordsOptions): string;
declare function generate(count?: number): string[];
declare function generate(options: GenerateOptions): string[];
declare function generate(options: JoinedWordsOptions): string;
export const wordsList: string[];
export default words;
declare const wordsList: string[];
declare type CountOptions = {
minLength?: number;
maxLength?: number;
};
declare function count(options?: CountOptions): number;
export { generate, count, wordsList };

@@ -1,272 +0,1991 @@

var seedrandom = require('seedrandom');
import seedrandom from "seedrandom";
var wordList = [
// Borrowed from xkcd password generator which borrowed it from wherever
"ability","able","aboard","about","above","accept","accident","according",
"account","accurate","acres","across","act","action","active","activity",
"actual","actually","add","addition","additional","adjective","adult","adventure",
"advice","affect","afraid","after","afternoon","again","against","age",
"ago","agree","ahead","aid","air","airplane","alike","alive",
"all","allow","almost","alone","along","aloud","alphabet","already",
"also","although","am","among","amount","ancient","angle","angry",
"animal","announced","another","answer","ants","any","anybody","anyone",
"anything","anyway","anywhere","apart","apartment","appearance","apple","applied",
"appropriate","are","area","arm","army","around","arrange","arrangement",
"arrive","arrow","art","article","as","aside","ask","asleep",
"at","ate","atmosphere","atom","atomic","attached","attack","attempt",
"attention","audience","author","automobile","available","average","avoid","aware",
"away","baby","back","bad","badly","bag","balance","ball",
"balloon","band","bank","bar","bare","bark","barn","base",
"baseball","basic","basis","basket","bat","battle","be","bean",
"bear","beat","beautiful","beauty","became","because","become","becoming",
"bee","been","before","began","beginning","begun","behavior","behind",
"being","believed","bell","belong","below","belt","bend","beneath",
"bent","beside","best","bet","better","between","beyond","bicycle",
"bigger","biggest","bill","birds","birth","birthday","bit","bite",
"black","blank","blanket","blew","blind","block","blood","blow",
"blue","board","boat","body","bone","book","border","born",
"both","bottle","bottom","bound","bow","bowl","box","boy",
"brain","branch","brass","brave","bread","break","breakfast","breath",
"breathe","breathing","breeze","brick","bridge","brief","bright","bring",
"broad","broke","broken","brother","brought","brown","brush","buffalo",
"build","building","built","buried","burn","burst","bus","bush",
"business","busy","but","butter","buy","by","cabin","cage",
"cake","call","calm","came","camera","camp","can","canal",
"cannot","cap","capital","captain","captured","car","carbon","card",
"care","careful","carefully","carried","carry","case","cast","castle",
"cat","catch","cattle","caught","cause","cave","cell","cent",
"center","central","century","certain","certainly","chain","chair","chamber",
"chance","change","changing","chapter","character","characteristic","charge","chart",
"check","cheese","chemical","chest","chicken","chief","child","children",
"choice","choose","chose","chosen","church","circle","circus","citizen",
"city","class","classroom","claws","clay","clean","clear","clearly",
"climate","climb","clock","close","closely","closer","cloth","clothes",
"clothing","cloud","club","coach","coal","coast","coat","coffee",
"cold","collect","college","colony","color","column","combination","combine",
"come","comfortable","coming","command","common","community","company","compare",
"compass","complete","completely","complex","composed","composition","compound","concerned",
"condition","congress","connected","consider","consist","consonant","constantly","construction",
"contain","continent","continued","contrast","control","conversation","cook","cookies",
"cool","copper","copy","corn","corner","correct","correctly","cost",
"cotton","could","count","country","couple","courage","course","court",
"cover","cow","cowboy","crack","cream","create","creature","crew",
"crop","cross","crowd","cry","cup","curious","current","curve",
"customs","cut","cutting","daily","damage","dance","danger","dangerous",
"dark","darkness","date","daughter","dawn","day","dead","deal",
"dear","death","decide","declared","deep","deeply","deer","definition",
"degree","depend","depth","describe","desert","design","desk","detail",
"determine","develop","development","diagram","diameter","did","die","differ",
"difference","different","difficult","difficulty","dig","dinner","direct","direction",
"directly","dirt","dirty","disappear","discover","discovery","discuss","discussion",
"disease","dish","distance","distant","divide","division","do","doctor",
"does","dog","doing","doll","dollar","done","donkey","door",
"dot","double","doubt","down","dozen","draw","drawn","dream",
"dress","drew","dried","drink","drive","driven","driver","driving",
"drop","dropped","drove","dry","duck","due","dug","dull",
"during","dust","duty","each","eager","ear","earlier","early",
"earn","earth","easier","easily","east","easy","eat","eaten",
"edge","education","effect","effort","egg","eight","either","electric",
"electricity","element","elephant","eleven","else","empty","end","enemy",
"energy","engine","engineer","enjoy","enough","enter","entire","entirely",
"environment","equal","equally","equator","equipment","escape","especially","essential",
"establish","even","evening","event","eventually","ever","every","everybody",
"everyone","everything","everywhere","evidence","exact","exactly","examine","example",
"excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise",
"exist","expect","experience","experiment","explain","explanation","explore","express",
"expression","extra","eye","face","facing","fact","factor","factory",
"failed","fair","fairly","fall","fallen","familiar","family","famous",
"far","farm","farmer","farther","fast","fastened","faster","fat",
"father","favorite","fear","feathers","feature","fed","feed","feel",
"feet","fell","fellow","felt","fence","few","fewer","field",
"fierce","fifteen","fifth","fifty","fight","fighting","figure","fill",
"film","final","finally","find","fine","finest","finger","finish",
"fire","fireplace","firm","first","fish","five","fix","flag",
"flame","flat","flew","flies","flight","floating","floor","flow",
"flower","fly","fog","folks","follow","food","foot","football",
"for","force","foreign","forest","forget","forgot","forgotten","form",
"former","fort","forth","forty","forward","fought","found","four",
"fourth","fox","frame","free","freedom","frequently","fresh","friend",
"friendly","frighten","frog","from","front","frozen","fruit","fuel",
"full","fully","fun","function","funny","fur","furniture","further",
"future","gain","game","garage","garden","gas","gasoline","gate",
"gather","gave","general","generally","gentle","gently","get","getting",
"giant","gift","girl","give","given","giving","glad","glass",
"globe","go","goes","gold","golden","gone","good","goose",
"got","government","grabbed","grade","gradually","grain","grandfather","grandmother",
"graph","grass","gravity","gray","great","greater","greatest","greatly",
"green","grew","ground","group","grow","grown","growth","guard",
"guess","guide","gulf","gun","habit","had","hair","half",
"halfway","hall","hand","handle","handsome","hang","happen","happened",
"happily","happy","harbor","hard","harder","hardly","has","hat",
"have","having","hay","he","headed","heading","health","heard",
"hearing","heart","heat","heavy","height","held","hello","help",
"helpful","her","herd","here","herself","hidden","hide","high",
"higher","highest","highway","hill","him","himself","his","history",
"hit","hold","hole","hollow","home","honor","hope","horn",
"horse","hospital","hot","hour","house","how","however","huge",
"human","hundred","hung","hungry","hunt","hunter","hurried","hurry",
"hurt","husband","ice","idea","identity","if","ill","image",
"imagine","immediately","importance","important","impossible","improve","in","inch",
"include","including","income","increase","indeed","independent","indicate","individual",
"industrial","industry","influence","information","inside","instance","instant","instead",
"instrument","interest","interior","into","introduced","invented","involved","iron",
"is","island","it","its","itself","jack","jar","jet",
"job","join","joined","journey","joy","judge","jump","jungle",
"just","keep","kept","key","kids","kill","kind","kitchen",
"knew","knife","know","knowledge","known","label","labor","lack",
"lady","laid","lake","lamp","land","language","large","larger",
"largest","last","late","later","laugh","law","lay","layers",
"lead","leader","leaf","learn","least","leather","leave","leaving",
"led","left","leg","length","lesson","let","letter","level",
"library","lie","life","lift","light","like","likely","limited",
"line","lion","lips","liquid","list","listen","little","live",
"living","load","local","locate","location","log","lonely","long",
"longer","look","loose","lose","loss","lost","lot","loud",
"love","lovely","low","lower","luck","lucky","lunch","lungs",
"lying","machine","machinery","mad","made","magic","magnet","mail",
"main","mainly","major","make","making","man","managed","manner",
"manufacturing","many","map","mark","market","married","mass","massage",
"master","material","mathematics","matter","may","maybe","me","meal",
"mean","means","meant","measure","meat","medicine","meet","melted",
"member","memory","men","mental","merely","met","metal","method",
"mice","middle","might","mighty","mile","military","milk","mill",
"mind","mine","minerals","minute","mirror","missing","mission","mistake",
"mix","mixture","model","modern","molecular","moment","money","monkey",
"month","mood","moon","more","morning","most","mostly","mother",
"motion","motor","mountain","mouse","mouth","move","movement","movie",
"moving","mud","muscle","music","musical","must","my","myself",
"mysterious","nails","name","nation","national","native","natural","naturally",
"nature","near","nearby","nearer","nearest","nearly","necessary","neck",
"needed","needle","needs","negative","neighbor","neighborhood","nervous","nest",
"never","new","news","newspaper","next","nice","night","nine",
"no","nobody","nodded","noise","none","noon","nor","north",
"nose","not","note","noted","nothing","notice","noun","now",
"number","numeral","nuts","object","observe","obtain","occasionally","occur",
"ocean","of","off","offer","office","officer","official","oil",
"old","older","oldest","on","once","one","only","onto",
"open","operation","opinion","opportunity","opposite","or","orange","orbit",
"order","ordinary","organization","organized","origin","original","other","ought",
"our","ourselves","out","outer","outline","outside","over","own",
"owner","oxygen","pack","package","page","paid","pain","paint",
"pair","palace","pale","pan","paper","paragraph","parallel","parent",
"park","part","particles","particular","particularly","partly","parts","party",
"pass","passage","past","path","pattern","pay","peace","pen",
"pencil","people","per","percent","perfect","perfectly","perhaps","period",
"person","personal","pet","phrase","physical","piano","pick","picture",
"pictured","pie","piece","pig","pile","pilot","pine","pink",
"pipe","pitch","place","plain","plan","plane","planet","planned",
"planning","plant","plastic","plate","plates","play","pleasant","please",
"pleasure","plenty","plural","plus","pocket","poem","poet","poetry",
"point","pole","police","policeman","political","pond","pony","pool",
"poor","popular","population","porch","port","position","positive","possible",
"possibly","post","pot","potatoes","pound","pour","powder","power",
"powerful","practical","practice","prepare","present","president","press","pressure",
"pretty","prevent","previous","price","pride","primitive","principal","principle",
"printed","private","prize","probably","problem","process","produce","product",
"production","program","progress","promised","proper","properly","property","protection",
"proud","prove","provide","public","pull","pupil","pure","purple",
"purpose","push","put","putting","quarter","queen","question","quick",
"quickly","quiet","quietly","quite","rabbit","race","radio","railroad",
"rain","raise","ran","ranch","range","rapidly","rate","rather",
"raw","rays","reach","read","reader","ready","real","realize",
"rear","reason","recall","receive","recent","recently","recognize","record",
"red","refer","refused","region","regular","related","relationship","religious",
"remain","remarkable","remember","remove","repeat","replace","replied","report",
"represent","require","research","respect","rest","result","return","review",
"rhyme","rhythm","rice","rich","ride","riding","right","ring",
"rise","rising","river","road","roar","rock","rocket","rocky",
"rod","roll","roof","room","root","rope","rose","rough",
"round","route","row","rubbed","rubber","rule","ruler","run",
"running","rush","sad","saddle","safe","safety","said","sail",
"sale","salmon","salt","same","sand","sang","sat","satellites",
"satisfied","save","saved","saw","say","scale","scared","scene",
"school","science","scientific","scientist","score","screen","sea","search",
"season","seat","second","secret","section","see","seed","seeing",
"seems","seen","seldom","select","selection","sell","send","sense",
"sent","sentence","separate","series","serious","serve","service","sets",
"setting","settle","settlers","seven","several","shade","shadow","shake",
"shaking","shall","shallow","shape","share","sharp","she","sheep",
"sheet","shelf","shells","shelter","shine","shinning","ship","shirt",
"shoe","shoot","shop","shore","short","shorter","shot","should",
"shoulder","shout","show","shown","shut","sick","sides","sight",
"sign","signal","silence","silent","silk","silly","silver","similar",
"simple","simplest","simply","since","sing","single","sink","sister",
"sit","sitting","situation","six","size","skill","skin","sky",
"slabs","slave","sleep","slept","slide","slight","slightly","slip",
"slipped","slope","slow","slowly","small","smaller","smallest","smell",
"smile","smoke","smooth","snake","snow","so","soap","social",
"society","soft","softly","soil","solar","sold","soldier","solid",
"solution","solve","some","somebody","somehow","someone","something","sometime",
"somewhere","son","song","soon","sort","sound","source","south",
"southern","space","speak","special","species","specific","speech","speed",
"spell","spend","spent","spider","spin","spirit","spite","split",
"spoken","sport","spread","spring","square","stage","stairs","stand",
"standard","star","stared","start","state","statement","station","stay",
"steady","steam","steel","steep","stems","step","stepped","stick",
"stiff","still","stock","stomach","stone","stood","stop","stopped",
"store","storm","story","stove","straight","strange","stranger","straw",
"stream","street","strength","stretch","strike","string","strip","strong",
"stronger","struck","structure","struggle","stuck","student","studied","studying",
"subject","substance","success","successful","such","sudden","suddenly","sugar",
"suggest","suit","sum","summer","sun","sunlight","supper","supply",
"support","suppose","sure","surface","surprise","surrounded","swam","sweet",
"swept","swim","swimming","swing","swung","syllable","symbol","system",
"table","tail","take","taken","tales","talk","tall","tank",
"tape","task","taste","taught","tax","tea","teach","teacher",
"team","tears","teeth","telephone","television","tell","temperature","ten",
"tent","term","terrible","test","than","thank","that","thee",
"them","themselves","then","theory","there","therefore","these","they",
"thick","thin","thing","think","third","thirty","this","those",
"thou","though","thought","thousand","thread","three","threw","throat",
"through","throughout","throw","thrown","thumb","thus","thy","tide",
"tie","tight","tightly","till","time","tin","tiny","tip",
"tired","title","to","tobacco","today","together","told","tomorrow",
"tone","tongue","tonight","too","took","tool","top","topic",
"torn","total","touch","toward","tower","town","toy","trace",
"track","trade","traffic","trail","train","transportation","trap","travel",
"treated","tree","triangle","tribe","trick","tried","trip","troops",
"tropical","trouble","truck","trunk","truth","try","tube","tune",
"turn","twelve","twenty","twice","two","type","typical","uncle",
"under","underline","understanding","unhappy","union","unit","universe","unknown",
"unless","until","unusual","up","upon","upper","upward","us",
"use","useful","using","usual","usually","valley","valuable","value",
"vapor","variety","various","vast","vegetable","verb","vertical","very",
"vessels","victory","view","village","visit","visitor","voice","volume",
"vote","vowel","voyage","wagon","wait","walk","wall","want",
"war","warm","warn","was","wash","waste","watch","water",
"wave","way","we","weak","wealth","wear","weather","week",
"weigh","weight","welcome","well","went","were","west","western",
"wet","whale","what","whatever","wheat","wheel","when","whenever",
"where","wherever","whether","which","while","whispered","whistle","white",
"who","whole","whom","whose","why","wide","widely","wife",
"wild","will","willing","win","wind","window","wing","winter",
"wire","wise","wish","with","within","without","wolf","women",
"won","wonder","wonderful","wood","wooden","wool","word","wore",
"work","worker","world","worried","worry","worse","worth","would",
"wrapped","write","writer","writing","written","wrong","wrote","yard",
"year","yellow","yes","yesterday","yet","you","young","younger",
"your","yourself","youth","zero","zebra","zipper","zoo","zulu"
// Export the word list as it is often useful
export const wordList = [
"ability",
"able",
"aboard",
"about",
"above",
"accept",
"accident",
"according",
"account",
"accurate",
"acres",
"across",
"act",
"action",
"active",
"activity",
"actual",
"actually",
"add",
"addition",
"additional",
"adjective",
"adult",
"adventure",
"advice",
"affect",
"afraid",
"after",
"afternoon",
"again",
"against",
"age",
"ago",
"agree",
"ahead",
"aid",
"air",
"airplane",
"alike",
"alive",
"all",
"allow",
"almost",
"alone",
"along",
"aloud",
"alphabet",
"already",
"also",
"although",
"am",
"among",
"amount",
"ancient",
"angle",
"angry",
"animal",
"announced",
"another",
"answer",
"ants",
"any",
"anybody",
"anyone",
"anything",
"anyway",
"anywhere",
"apart",
"apartment",
"appearance",
"apple",
"applied",
"appropriate",
"are",
"area",
"arm",
"army",
"around",
"arrange",
"arrangement",
"arrive",
"arrow",
"art",
"article",
"as",
"aside",
"ask",
"asleep",
"at",
"ate",
"atmosphere",
"atom",
"atomic",
"attached",
"attack",
"attempt",
"attention",
"audience",
"author",
"automobile",
"available",
"average",
"avoid",
"aware",
"away",
"baby",
"back",
"bad",
"badly",
"bag",
"balance",
"ball",
"balloon",
"band",
"bank",
"bar",
"bare",
"bark",
"barn",
"base",
"baseball",
"basic",
"basis",
"basket",
"bat",
"battle",
"be",
"bean",
"bear",
"beat",
"beautiful",
"beauty",
"became",
"because",
"become",
"becoming",
"bee",
"been",
"before",
"began",
"beginning",
"begun",
"behavior",
"behind",
"being",
"believed",
"bell",
"belong",
"below",
"belt",
"bend",
"beneath",
"bent",
"beside",
"best",
"bet",
"better",
"between",
"beyond",
"bicycle",
"bigger",
"biggest",
"bill",
"birds",
"birth",
"birthday",
"bit",
"bite",
"black",
"blank",
"blanket",
"blew",
"blind",
"block",
"blood",
"blow",
"blue",
"board",
"boat",
"body",
"bone",
"book",
"border",
"born",
"both",
"bottle",
"bottom",
"bound",
"bow",
"bowl",
"box",
"boy",
"brain",
"branch",
"brass",
"brave",
"bread",
"break",
"breakfast",
"breath",
"breathe",
"breathing",
"breeze",
"brick",
"bridge",
"brief",
"bright",
"bring",
"broad",
"broke",
"broken",
"brother",
"brought",
"brown",
"brush",
"buffalo",
"build",
"building",
"built",
"buried",
"burn",
"burst",
"bus",
"bush",
"business",
"busy",
"but",
"butter",
"buy",
"by",
"cabin",
"cage",
"cake",
"call",
"calm",
"came",
"camera",
"camp",
"can",
"canal",
"cannot",
"cap",
"capital",
"captain",
"captured",
"car",
"carbon",
"card",
"care",
"careful",
"carefully",
"carried",
"carry",
"case",
"cast",
"castle",
"cat",
"catch",
"cattle",
"caught",
"cause",
"cave",
"cell",
"cent",
"center",
"central",
"century",
"certain",
"certainly",
"chain",
"chair",
"chamber",
"chance",
"change",
"changing",
"chapter",
"character",
"characteristic",
"charge",
"chart",
"check",
"cheese",
"chemical",
"chest",
"chicken",
"chief",
"child",
"children",
"choice",
"choose",
"chose",
"chosen",
"church",
"circle",
"circus",
"citizen",
"city",
"class",
"classroom",
"claws",
"clay",
"clean",
"clear",
"clearly",
"climate",
"climb",
"clock",
"close",
"closely",
"closer",
"cloth",
"clothes",
"clothing",
"cloud",
"club",
"coach",
"coal",
"coast",
"coat",
"coffee",
"cold",
"collect",
"college",
"colony",
"color",
"column",
"combination",
"combine",
"come",
"comfortable",
"coming",
"command",
"common",
"community",
"company",
"compare",
"compass",
"complete",
"completely",
"complex",
"composed",
"composition",
"compound",
"concerned",
"condition",
"congress",
"connected",
"consider",
"consist",
"consonant",
"constantly",
"construction",
"contain",
"continent",
"continued",
"contrast",
"control",
"conversation",
"cook",
"cookies",
"cool",
"copper",
"copy",
"corn",
"corner",
"correct",
"correctly",
"cost",
"cotton",
"could",
"count",
"country",
"couple",
"courage",
"course",
"court",
"cover",
"cow",
"cowboy",
"crack",
"cream",
"create",
"creature",
"crew",
"crop",
"cross",
"crowd",
"cry",
"cup",
"curious",
"current",
"curve",
"customs",
"cut",
"cutting",
"daily",
"damage",
"dance",
"danger",
"dangerous",
"dark",
"darkness",
"date",
"daughter",
"dawn",
"day",
"dead",
"deal",
"dear",
"death",
"decide",
"declared",
"deep",
"deeply",
"deer",
"definition",
"degree",
"depend",
"depth",
"describe",
"desert",
"design",
"desk",
"detail",
"determine",
"develop",
"development",
"diagram",
"diameter",
"did",
"die",
"differ",
"difference",
"different",
"difficult",
"difficulty",
"dig",
"dinner",
"direct",
"direction",
"directly",
"dirt",
"dirty",
"disappear",
"discover",
"discovery",
"discuss",
"discussion",
"disease",
"dish",
"distance",
"distant",
"divide",
"division",
"do",
"doctor",
"does",
"dog",
"doing",
"doll",
"dollar",
"done",
"donkey",
"door",
"dot",
"double",
"doubt",
"down",
"dozen",
"draw",
"drawn",
"dream",
"dress",
"drew",
"dried",
"drink",
"drive",
"driven",
"driver",
"driving",
"drop",
"dropped",
"drove",
"dry",
"duck",
"due",
"dug",
"dull",
"during",
"dust",
"duty",
"each",
"eager",
"ear",
"earlier",
"early",
"earn",
"earth",
"easier",
"easily",
"east",
"easy",
"eat",
"eaten",
"edge",
"education",
"effect",
"effort",
"egg",
"eight",
"either",
"electric",
"electricity",
"element",
"elephant",
"eleven",
"else",
"empty",
"end",
"enemy",
"energy",
"engine",
"engineer",
"enjoy",
"enough",
"enter",
"entire",
"entirely",
"environment",
"equal",
"equally",
"equator",
"equipment",
"escape",
"especially",
"essential",
"establish",
"even",
"evening",
"event",
"eventually",
"ever",
"every",
"everybody",
"everyone",
"everything",
"everywhere",
"evidence",
"exact",
"exactly",
"examine",
"example",
"excellent",
"except",
"exchange",
"excited",
"excitement",
"exciting",
"exclaimed",
"exercise",
"exist",
"expect",
"experience",
"experiment",
"explain",
"explanation",
"explore",
"express",
"expression",
"extra",
"eye",
"face",
"facing",
"fact",
"factor",
"factory",
"failed",
"fair",
"fairly",
"fall",
"fallen",
"familiar",
"family",
"famous",
"far",
"farm",
"farmer",
"farther",
"fast",
"fastened",
"faster",
"fat",
"father",
"favorite",
"fear",
"feathers",
"feature",
"fed",
"feed",
"feel",
"feet",
"fell",
"fellow",
"felt",
"fence",
"few",
"fewer",
"field",
"fierce",
"fifteen",
"fifth",
"fifty",
"fight",
"fighting",
"figure",
"fill",
"film",
"final",
"finally",
"find",
"fine",
"finest",
"finger",
"finish",
"fire",
"fireplace",
"firm",
"first",
"fish",
"five",
"fix",
"flag",
"flame",
"flat",
"flew",
"flies",
"flight",
"floating",
"floor",
"flow",
"flower",
"fly",
"fog",
"folks",
"follow",
"food",
"foot",
"football",
"for",
"force",
"foreign",
"forest",
"forget",
"forgot",
"forgotten",
"form",
"former",
"fort",
"forth",
"forty",
"forward",
"fought",
"found",
"four",
"fourth",
"fox",
"frame",
"free",
"freedom",
"frequently",
"fresh",
"friend",
"friendly",
"frighten",
"frog",
"from",
"front",
"frozen",
"fruit",
"fuel",
"full",
"fully",
"fun",
"function",
"funny",
"fur",
"furniture",
"further",
"future",
"gain",
"game",
"garage",
"garden",
"gas",
"gasoline",
"gate",
"gather",
"gave",
"general",
"generally",
"gentle",
"gently",
"get",
"getting",
"giant",
"gift",
"girl",
"give",
"given",
"giving",
"glad",
"glass",
"globe",
"go",
"goes",
"gold",
"golden",
"gone",
"good",
"goose",
"got",
"government",
"grabbed",
"grade",
"gradually",
"grain",
"grandfather",
"grandmother",
"graph",
"grass",
"gravity",
"gray",
"great",
"greater",
"greatest",
"greatly",
"green",
"grew",
"ground",
"group",
"grow",
"grown",
"growth",
"guard",
"guess",
"guide",
"gulf",
"gun",
"habit",
"had",
"hair",
"half",
"halfway",
"hall",
"hand",
"handle",
"handsome",
"hang",
"happen",
"happened",
"happily",
"happy",
"harbor",
"hard",
"harder",
"hardly",
"has",
"hat",
"have",
"having",
"hay",
"he",
"headed",
"heading",
"health",
"heard",
"hearing",
"heart",
"heat",
"heavy",
"height",
"held",
"hello",
"help",
"helpful",
"her",
"herd",
"here",
"herself",
"hidden",
"hide",
"high",
"higher",
"highest",
"highway",
"hill",
"him",
"himself",
"his",
"history",
"hit",
"hold",
"hole",
"hollow",
"home",
"honor",
"hope",
"horn",
"horse",
"hospital",
"hot",
"hour",
"house",
"how",
"however",
"huge",
"human",
"hundred",
"hung",
"hungry",
"hunt",
"hunter",
"hurried",
"hurry",
"hurt",
"husband",
"ice",
"idea",
"identity",
"if",
"ill",
"image",
"imagine",
"immediately",
"importance",
"important",
"impossible",
"improve",
"in",
"inch",
"include",
"including",
"income",
"increase",
"indeed",
"independent",
"indicate",
"individual",
"industrial",
"industry",
"influence",
"information",
"inside",
"instance",
"instant",
"instead",
"instrument",
"interest",
"interior",
"into",
"introduced",
"invented",
"involved",
"iron",
"is",
"island",
"it",
"its",
"itself",
"jack",
"jar",
"jet",
"job",
"join",
"joined",
"journey",
"joy",
"judge",
"jump",
"jungle",
"just",
"keep",
"kept",
"key",
"kids",
"kill",
"kind",
"kitchen",
"knew",
"knife",
"know",
"knowledge",
"known",
"label",
"labor",
"lack",
"lady",
"laid",
"lake",
"lamp",
"land",
"language",
"large",
"larger",
"largest",
"last",
"late",
"later",
"laugh",
"law",
"lay",
"layers",
"lead",
"leader",
"leaf",
"learn",
"least",
"leather",
"leave",
"leaving",
"led",
"left",
"leg",
"length",
"lesson",
"let",
"letter",
"level",
"library",
"lie",
"life",
"lift",
"light",
"like",
"likely",
"limited",
"line",
"lion",
"lips",
"liquid",
"list",
"listen",
"little",
"live",
"living",
"load",
"local",
"locate",
"location",
"log",
"lonely",
"long",
"longer",
"look",
"loose",
"lose",
"loss",
"lost",
"lot",
"loud",
"love",
"lovely",
"low",
"lower",
"luck",
"lucky",
"lunch",
"lungs",
"lying",
"machine",
"machinery",
"mad",
"made",
"magic",
"magnet",
"mail",
"main",
"mainly",
"major",
"make",
"making",
"man",
"managed",
"manner",
"manufacturing",
"many",
"map",
"mark",
"market",
"married",
"mass",
"massage",
"master",
"material",
"mathematics",
"matter",
"may",
"maybe",
"me",
"meal",
"mean",
"means",
"meant",
"measure",
"meat",
"medicine",
"meet",
"melted",
"member",
"memory",
"men",
"mental",
"merely",
"met",
"metal",
"method",
"mice",
"middle",
"might",
"mighty",
"mile",
"military",
"milk",
"mill",
"mind",
"mine",
"minerals",
"minute",
"mirror",
"missing",
"mission",
"mistake",
"mix",
"mixture",
"model",
"modern",
"molecular",
"moment",
"money",
"monkey",
"month",
"mood",
"moon",
"more",
"morning",
"most",
"mostly",
"mother",
"motion",
"motor",
"mountain",
"mouse",
"mouth",
"move",
"movement",
"movie",
"moving",
"mud",
"muscle",
"music",
"musical",
"must",
"my",
"myself",
"mysterious",
"nails",
"name",
"nation",
"national",
"native",
"natural",
"naturally",
"nature",
"near",
"nearby",
"nearer",
"nearest",
"nearly",
"necessary",
"neck",
"needed",
"needle",
"needs",
"negative",
"neighbor",
"neighborhood",
"nervous",
"nest",
"never",
"new",
"news",
"newspaper",
"next",
"nice",
"night",
"nine",
"no",
"nobody",
"nodded",
"noise",
"none",
"noon",
"nor",
"north",
"nose",
"not",
"note",
"noted",
"nothing",
"notice",
"noun",
"now",
"number",
"numeral",
"nuts",
"object",
"observe",
"obtain",
"occasionally",
"occur",
"ocean",
"of",
"off",
"offer",
"office",
"officer",
"official",
"oil",
"old",
"older",
"oldest",
"on",
"once",
"one",
"only",
"onto",
"open",
"operation",
"opinion",
"opportunity",
"opposite",
"or",
"orange",
"orbit",
"order",
"ordinary",
"organization",
"organized",
"origin",
"original",
"other",
"ought",
"our",
"ourselves",
"out",
"outer",
"outline",
"outside",
"over",
"own",
"owner",
"oxygen",
"pack",
"package",
"page",
"paid",
"pain",
"paint",
"pair",
"palace",
"pale",
"pan",
"paper",
"paragraph",
"parallel",
"parent",
"park",
"part",
"particles",
"particular",
"particularly",
"partly",
"parts",
"party",
"pass",
"passage",
"past",
"path",
"pattern",
"pay",
"peace",
"pen",
"pencil",
"people",
"per",
"percent",
"perfect",
"perfectly",
"perhaps",
"period",
"person",
"personal",
"pet",
"phrase",
"physical",
"piano",
"pick",
"picture",
"pictured",
"pie",
"piece",
"pig",
"pile",
"pilot",
"pine",
"pink",
"pipe",
"pitch",
"place",
"plain",
"plan",
"plane",
"planet",
"planned",
"planning",
"plant",
"plastic",
"plate",
"plates",
"play",
"pleasant",
"please",
"pleasure",
"plenty",
"plural",
"plus",
"pocket",
"poem",
"poet",
"poetry",
"point",
"pole",
"police",
"policeman",
"political",
"pond",
"pony",
"pool",
"poor",
"popular",
"population",
"porch",
"port",
"position",
"positive",
"possible",
"possibly",
"post",
"pot",
"potatoes",
"pound",
"pour",
"powder",
"power",
"powerful",
"practical",
"practice",
"prepare",
"present",
"president",
"press",
"pressure",
"pretty",
"prevent",
"previous",
"price",
"pride",
"primitive",
"principal",
"principle",
"printed",
"private",
"prize",
"probably",
"problem",
"process",
"produce",
"product",
"production",
"program",
"progress",
"promised",
"proper",
"properly",
"property",
"protection",
"proud",
"prove",
"provide",
"public",
"pull",
"pupil",
"pure",
"purple",
"purpose",
"push",
"put",
"putting",
"quarter",
"queen",
"question",
"quick",
"quickly",
"quiet",
"quietly",
"quite",
"rabbit",
"race",
"radio",
"railroad",
"rain",
"raise",
"ran",
"ranch",
"range",
"rapidly",
"rate",
"rather",
"raw",
"rays",
"reach",
"read",
"reader",
"ready",
"real",
"realize",
"rear",
"reason",
"recall",
"receive",
"recent",
"recently",
"recognize",
"record",
"red",
"refer",
"refused",
"region",
"regular",
"related",
"relationship",
"religious",
"remain",
"remarkable",
"remember",
"remove",
"repeat",
"replace",
"replied",
"report",
"represent",
"require",
"research",
"respect",
"rest",
"result",
"return",
"review",
"rhyme",
"rhythm",
"rice",
"rich",
"ride",
"riding",
"right",
"ring",
"rise",
"rising",
"river",
"road",
"roar",
"rock",
"rocket",
"rocky",
"rod",
"roll",
"roof",
"room",
"root",
"rope",
"rose",
"rough",
"round",
"route",
"row",
"rubbed",
"rubber",
"rule",
"ruler",
"run",
"running",
"rush",
"sad",
"saddle",
"safe",
"safety",
"said",
"sail",
"sale",
"salmon",
"salt",
"same",
"sand",
"sang",
"sat",
"satellites",
"satisfied",
"save",
"saved",
"saw",
"say",
"scale",
"scared",
"scene",
"school",
"science",
"scientific",
"scientist",
"score",
"screen",
"sea",
"search",
"season",
"seat",
"second",
"secret",
"section",
"see",
"seed",
"seeing",
"seems",
"seen",
"seldom",
"select",
"selection",
"sell",
"send",
"sense",
"sent",
"sentence",
"separate",
"series",
"serious",
"serve",
"service",
"sets",
"setting",
"settle",
"settlers",
"seven",
"several",
"shade",
"shadow",
"shake",
"shaking",
"shall",
"shallow",
"shape",
"share",
"sharp",
"she",
"sheep",
"sheet",
"shelf",
"shells",
"shelter",
"shine",
"shinning",
"ship",
"shirt",
"shoe",
"shoot",
"shop",
"shore",
"short",
"shorter",
"shot",
"should",
"shoulder",
"shout",
"show",
"shown",
"shut",
"sick",
"sides",
"sight",
"sign",
"signal",
"silence",
"silent",
"silk",
"silly",
"silver",
"similar",
"simple",
"simplest",
"simply",
"since",
"sing",
"single",
"sink",
"sister",
"sit",
"sitting",
"situation",
"six",
"size",
"skill",
"skin",
"sky",
"slabs",
"slave",
"sleep",
"slept",
"slide",
"slight",
"slightly",
"slip",
"slipped",
"slope",
"slow",
"slowly",
"small",
"smaller",
"smallest",
"smell",
"smile",
"smoke",
"smooth",
"snake",
"snow",
"so",
"soap",
"social",
"society",
"soft",
"softly",
"soil",
"solar",
"sold",
"soldier",
"solid",
"solution",
"solve",
"some",
"somebody",
"somehow",
"someone",
"something",
"sometime",
"somewhere",
"son",
"song",
"soon",
"sort",
"sound",
"source",
"south",
"southern",
"space",
"speak",
"special",
"species",
"specific",
"speech",
"speed",
"spell",
"spend",
"spent",
"spider",
"spin",
"spirit",
"spite",
"split",
"spoken",
"sport",
"spread",
"spring",
"square",
"stage",
"stairs",
"stand",
"standard",
"star",
"stared",
"start",
"state",
"statement",
"station",
"stay",
"steady",
"steam",
"steel",
"steep",
"stems",
"step",
"stepped",
"stick",
"stiff",
"still",
"stock",
"stomach",
"stone",
"stood",
"stop",
"stopped",
"store",
"storm",
"story",
"stove",
"straight",
"strange",
"stranger",
"straw",
"stream",
"street",
"strength",
"stretch",
"strike",
"string",
"strip",
"strong",
"stronger",
"struck",
"structure",
"struggle",
"stuck",
"student",
"studied",
"studying",
"subject",
"substance",
"success",
"successful",
"such",
"sudden",
"suddenly",
"sugar",
"suggest",
"suit",
"sum",
"summer",
"sun",
"sunlight",
"supper",
"supply",
"support",
"suppose",
"sure",
"surface",
"surprise",
"surrounded",
"swam",
"sweet",
"swept",
"swim",
"swimming",
"swing",
"swung",
"syllable",
"symbol",
"system",
"table",
"tail",
"take",
"taken",
"tales",
"talk",
"tall",
"tank",
"tape",
"task",
"taste",
"taught",
"tax",
"tea",
"teach",
"teacher",
"team",
"tears",
"teeth",
"telephone",
"television",
"tell",
"temperature",
"ten",
"tent",
"term",
"terrible",
"test",
"than",
"thank",
"that",
"thee",
"them",
"themselves",
"then",
"theory",
"there",
"therefore",
"these",
"they",
"thick",
"thin",
"thing",
"think",
"third",
"thirty",
"this",
"those",
"thou",
"though",
"thought",
"thousand",
"thread",
"three",
"threw",
"throat",
"through",
"throughout",
"throw",
"thrown",
"thumb",
"thus",
"thy",
"tide",
"tie",
"tight",
"tightly",
"till",
"time",
"tin",
"tiny",
"tip",
"tired",
"title",
"to",
"tobacco",
"today",
"together",
"told",
"tomorrow",
"tone",
"tongue",
"tonight",
"too",
"took",
"tool",
"top",
"topic",
"torn",
"total",
"touch",
"toward",
"tower",
"town",
"toy",
"trace",
"track",
"trade",
"traffic",
"trail",
"train",
"transportation",
"trap",
"travel",
"treated",
"tree",
"triangle",
"tribe",
"trick",
"tried",
"trip",
"troops",
"tropical",
"trouble",
"truck",
"trunk",
"truth",
"try",
"tube",
"tune",
"turn",
"twelve",
"twenty",
"twice",
"two",
"type",
"typical",
"uncle",
"under",
"underline",
"understanding",
"unhappy",
"union",
"unit",
"universe",
"unknown",
"unless",
"until",
"unusual",
"up",
"upon",
"upper",
"upward",
"us",
"use",
"useful",
"using",
"usual",
"usually",
"valley",
"valuable",
"value",
"vapor",
"variety",
"various",
"vast",
"vegetable",
"verb",
"vertical",
"very",
"vessels",
"victory",
"view",
"village",
"visit",
"visitor",
"voice",
"volume",
"vote",
"vowel",
"voyage",
"wagon",
"wait",
"walk",
"wall",
"want",
"war",
"warm",
"warn",
"was",
"wash",
"waste",
"watch",
"water",
"wave",
"way",
"we",
"weak",
"wealth",
"wear",
"weather",
"week",
"weigh",
"weight",
"welcome",
"well",
"went",
"were",
"west",
"western",
"wet",
"whale",
"what",
"whatever",
"wheat",
"wheel",
"when",
"whenever",
"where",
"wherever",
"whether",
"which",
"while",
"whispered",
"whistle",
"white",
"who",
"whole",
"whom",
"whose",
"why",
"wide",
"widely",
"wife",
"wild",
"will",
"willing",
"win",
"wind",
"window",
"wing",
"winter",
"wire",
"wise",
"wish",
"with",
"within",
"without",
"wolf",
"women",
"won",
"wonder",
"wonderful",
"wood",
"wooden",
"wool",
"word",
"wore",
"work",
"worker",
"world",
"worried",
"worry",
"worse",
"worth",
"would",
"wrapped",
"write",
"writer",
"writing",
"written",
"wrong",
"wrote",
"yard",
"year",
"yellow",
"yes",
"yesterday",
"yet",
"you",
"young",
"younger",
"your",
"yourself",
"youth",
"zero",
"zebra",
"zipper",
"zoo",
"zulu",
];
function words(options) {
const shortestWordSize = wordList.reduce((shortestWord, currentWord) =>
currentWord.length < shortestWord.length ? currentWord : shortestWord
).length;
const longestWordSize = wordList.reduce((longestWord, currentWord) =>
currentWord.length > longestWord.length ? currentWord : longestWord
).length;
export function generate(options) {
// initalize random number generator for words if options.seed is provided
const random = options?.seed ? new seedrandom(options.seed) : null;
const { minLength, maxLength, ...rest } = options || {};
function word() {
if (options && options.maxLength > 1) {
return generateWordWithMaxLength();
} else {
return generateRandomWord();
}
}
let min =
typeof minLength !== "number"
? shortestWordSize
: limitWordSize(minLength);
function generateWordWithMaxLength() {
var rightSize = false;
var wordUsed;
while (!rightSize) {
const max =
typeof maxLength !== "number"
? longestWordSize
: limitWordSize(maxLength);
if (min > max) min = max;
let rightSize = false;
let wordUsed;
while (!rightSize) {
wordUsed = generateRandomWord();
if(wordUsed.length <= options.maxLength) {
rightSize = true;
}
rightSize = wordUsed.length <= max && wordUsed.length >= min;
}

@@ -280,2 +1999,9 @@ return wordUsed;

// limits the size of words to the minimum and maximum possible
function limitWordSize(wordSize) {
if (wordSize < shortestWordSize) wordSize = shortestWordSize;
if (wordSize > longestWordSize) wordSize = longestWordSize;
return wordSize;
}
// random int as seeded by options.seed if applicable, or Math.random() otherwise

@@ -288,3 +2014,3 @@ function randInt(lessThan) {

// No arguments = generate one word
if (typeof(options) === 'undefined') {
if (options === undefined) {
return word();

@@ -294,4 +2020,6 @@ }

// Just a number = return that many words
if (typeof(options) === 'number') {
if (typeof options === "number") {
options = { exactly: options };
} else if (Object.keys(rest).length === 0) {
return word();
}

@@ -304,5 +2032,5 @@

}
// not a number = one word par string
if (typeof(options.wordsPerString) !== 'number') {
if (typeof options.wordsPerString !== "number") {
options.wordsPerString = 1;

@@ -312,3 +2040,3 @@ }

//not a function = returns the raw word
if (typeof(options.formatter) !== 'function') {
if (typeof options.formatter !== "function") {
options.formatter = (word) => word;

@@ -318,16 +2046,15 @@ }

//not a string = separator is a space
if (typeof(options.separator) !== 'string') {
options.separator = ' ';
if (typeof options.separator !== "string") {
options.separator = " ";
}
var total = options.min + randInt(options.max + 1 - options.min);
var results = [];
var token = '';
var relativeIndex = 0;
const total = options.min + randInt(options.max + 1 - options.min);
let results = [];
let token = "";
let relativeIndex = 0;
for (var i = 0; (i < total * options.wordsPerString); i++) {
for (let i = 0; i < total * options.wordsPerString; i++) {
if (relativeIndex === options.wordsPerString - 1) {
token += options.formatter(word(), relativeIndex);
}
else {
} else {
token += options.formatter(word(), relativeIndex) + options.separator;

@@ -338,8 +2065,7 @@ }

results.push(token);
token = '';
token = "";
relativeIndex = 0;
}
}
if (typeof options.join === 'string') {
if (typeof options.join === "string") {
results = results.join(options.join);

@@ -351,4 +2077,16 @@ }

module.exports = words;
// Export the word list as it is often useful
words.wordList = wordList;
export function count(options) {
let { minLength, maxLength } = options || {};
if (typeof minLength !== "number") {
minLength = shortestWordSize;
}
if (typeof maxLength !== "number") {
maxLength = longestWordSize;
}
return wordList.filter(
(word) => word.length >= minLength && word.length <= maxLength
).length;
}
{
"name": "random-words",
"version": "1.3.0",
"version": "2.0.0",
"description": "Generate one or more common English words",
"main": "index.js",
"types": "index.d.ts",
"type": "module",
"scripts": {

@@ -25,8 +26,8 @@ "test": "mocha tests/test.js"

"license": "MIT",
"devDependencies": {
"mocha": "^9.1.3"
},
"dependencies": {
"seedrandom": "^3.0.5"
},
"devDependencies": {
"mocha": "^10.2.0"
}
}

@@ -9,4 +9,6 @@ # random-words

The `seed` option can be used for situations that require deterministic output. When given the same `seed` with the same input, `randomWords()` will yield deterministic results, in regards to both actual word selection and the number of words returned (when using `min` and `max`). The underlying implementation of this option utilizes the [seedrandom](https://www.npmjs.com/package/seedrandom) package as a replacement for `Math.random()`.
The `seed` option can be used with the `generate` function for situations that require deterministic output. When given the same `seed` with the same input, `generate()` will yield deterministic results, in regards to both actual word selection and the number of words returned (when using `min` and `max`). The underlying implementation of this option utilizes the [seedrandom](https://www.npmjs.com/package/seedrandom) package as a replacement for `Math.random()`.
The `count` function can be used to calculate the total number of words in the word list that meet the specified minimum and maximum length criteria.
Installation:

@@ -18,44 +20,97 @@

var randomWords = require('random-words');
```js
import { generate, count } from "random-words";
console.log(randomWords());
army
console.log(generate());
//output: 'army'
console.log(randomWords(5));
['army', 'beautiful', 'became', 'if', 'actually']
console.log(generate(5));
//output: ['army', 'beautiful', 'became', 'if', 'actually']
console.log(randomWords({ min: 3, max: 10 }));
['became', 'arrow', 'article', 'therefore']
console.log(generate({ minLength: 2 }));
//output: 'hello'
console.log(randomWords({ exactly: 2 }));
['beside', 'between']
console.log(generate({ maxLength: 6 }));
//output: 'blue'
console.log(randomWords({ min: 2, max: 3, seed: 'my-seed' }));
['plenty', 'pure']
console.log(generate({ minLength: 5, maxLength: 5 }));
//output : 'world'
// this call will yield exactly the same results as the last since the same `seed` was used and the other inputs are identical
console.log(randomWords({ min: 2, max: 3, seed: 'my-seed' }));
['plenty', 'pure']
console.log(generate({ minLength: 11, maxLength: 10000 })); //maxLength limited to the longest possible word
//output: 'environment'
console.log(randomWords({ exactly: 5, join: ' ' }))
'army beautiful became if exactly'
console.log(randomWords({ exactly: 5, join: '' }))
'armybeautifulbecameifexactly'
console.log(generate({ minLength: 10000, maxLength: 5 })); //minLength limited to the maxLength
//output: 'short'
console.log(randomWords({exactly: 5, maxLength: 4}))
['army','come','eye','five','fur']
console.log(generate({ min: 3, max: 10 }));
//output: ['became', 'arrow', 'article', 'therefore']
console.log(randomWords({exactly:5, wordsPerString:2}))
[ 'salt practical', 'also brief', 'country muscle', 'neighborhood beyond', 'grew pig' ]
console.log(generate({ exactly: 2 }));
//output: ['beside', 'between']
console.log(randomWords({exactly:5, wordsPerString:2, separator:'-'}))
[ 'equator-variety', 'salt-usually', 'importance-becoming', 'stream-several', 'goes-fight' ]
console.log(generate({ min: 2, max: 3, seed: "my-seed" }));
//output: ['plenty', 'pure']
console.log(randomWords({exactly:5, wordsPerString:2, formatter: (word)=> word.toUpperCase()}))
[ 'HAVING LOAD', 'LOST PINE', 'GAME SLOPE', 'SECRET GIANT', 'INDEED LOCATION' ]
// this call will yield exactly the same results as the last since the same `seed` was used and the other inputs are identical
console.log(generate({ min: 2, max: 3, seed: "my-seed" }));
//output: ['plenty', 'pure']
console.log(randomWords({exactly:5, wordsPerString:2, formatter: (word, index)=> {
return index === 0 ? word.slice(0,1).toUpperCase().concat(word.slice(1)) : word;
}}))
[ 'Until smoke', 'Year strength', 'Pay knew', 'Fallen must', 'Chief arrow' ]
console.log(generate({ exactly: 5, join: " " }));
//output: 'army beautiful became if exactly'
console.log(generate({ exactly: 5, join: "" }));
//output: 'armybeautifulbecameifexactly'
console.log(generate({ exactly: 2, minLength: 4 }));
//output: ['atom', 'window']
console.log(generate({ exactly: 5, maxLength: 4 }));
//output: ['army', 'come', 'eye', 'five', 'fur']
console.log(generate({ exactly: 2, minLength: 3, maxLength: 3 }));
//output: ['you, 'are']
console.log(generate({ exactly: 3, minLength: 5, maxLength: 100000 }));
//output: ['understanding', 'should', 'yourself']
console.log(generate({ exactly: 5, wordsPerString: 2 }));
//output: [ 'salt practical', 'also brief', 'country muscle', 'neighborhood beyond', 'grew pig' ]
console.log(generate({ exactly: 5, wordsPerString: 2, separator: "-" }));
//output: [ 'equator-variety', 'salt-usually', 'importance-becoming', 'stream-several', 'goes-fight' ]
console.log(
generate({
exactly: 5,
wordsPerString: 2,
formatter: (word) => word.toUpperCase(),
})
);
//output: [ 'HAVING LOAD', 'LOST PINE', 'GAME SLOPE', 'SECRET GIANT', 'INDEED LOCATION' ]
console.log(
generate({
exactly: 5,
wordsPerString: 2,
formatter: (word, index) => {
return index === 0
? word.slice(0, 1).toUpperCase().concat(word.slice(1))
: word;
},
})
);
//output: [ 'Until smoke', 'Year strength', 'Pay knew', 'Fallen must', 'Chief arrow' ]
console.log(count());
//output: 1952
console.log(count({ minLength: 5 }));
//output: 1318
console.log(count({ maxLength: 7 }));
//output: 1649
console.log(count({ minLength: 5, maxLength: 7 }));
//output: 1015
```

@@ -1,131 +0,295 @@

var assert = require('assert');
var randomWords = require('../index.js');
import assert from "assert";
import { generate, count } from "../index.js";
import { wordList } from "../index.js";
describe('random-words', function () {
it('should return one word when called with no arguments', function () {
var word = randomWords();
assert.ok(typeof(word) === 'string', 'word is a string');
assert.ok(word.length, 'word is not empty');
assert.ok(word.indexOf(' ') === -1, 'word does not contain spaces');
const longestWordSize = wordList.reduce((longestWord, currentWord) =>
currentWord.length > longestWord.length ? currentWord : longestWord
).length;
describe("random-words : generate", function () {
it("should return one word when called with no arguments", function () {
const word = generate();
assert.ok(typeof word === "string", "word is a string");
assert.ok(word.length, "word is not empty");
assert.ok(word.indexOf(" ") === -1, "word does not contain spaces");
});
it("should return 5 words when called with the number 5", function () {
const words = generate(5);
assert.ok(words.length === 5, "contains 5 elements");
});
it("should return between 5 and 10 words when called with min: 5 and max: 10", function () {
const words = generate({ min: 5, max: 10 });
assert.ok(words.length >= 5 && words.length <= 10);
});
it("returns result of variable length when called with min: 5 and max: 10", function () {
const lengths = {};
for (let i = 0; i < 100; i++) {
const words = generate({ min: 5, max: 10 });
lengths[words.length] = true;
}
assert.ok(Object.keys(lengths).length > 1, "result varies in length");
});
it("should return 5 space separated words when join is used with exactly: 5", function () {
let phrase = generate({ exactly: 5, join: " " });
assert.ok(typeof phrase === "string", "result is a string");
assert.ok(phrase.match(/\S/), "result contains text, not just spaces");
phrase = phrase.replace(/[\S]/g, "");
assert.ok(
phrase.length === 4,
"result contains 4 spaces joining the 5 words"
);
});
it("should return 5 concatenated words when join is used with an empty string and exactly: 5", function () {
const phrase = generate({ exactly: 5, join: "" });
assert.ok(typeof phrase === "string", "result is a string");
assert.ok(phrase.match(/\w/), "result contains text, no spaces");
});
it("should return 5 words when called with exactly: 5 and join: false", function () {
const words = generate({ exactly: 5, join: false });
assert.ok(words.length === 5, "contains 5 elements");
});
it("should return 5 words when called with exactly: 5 and join: null", function () {
const words = generate({ exactly: 5, join: null });
assert.ok(words.length === 5, "contains 5 elements");
});
it("should return one word with a minimum of 8 letters", function () {
const minWordSize = 8;
const word = generate({ minLength: minWordSize });
assert.ok(word.length >= minWordSize, "result is less than 8 letters");
});
it("should return one word with a maximum of 5 letters", function () {
const maxWordSize = 5;
const word = generate({ maxLength: maxWordSize });
assert.ok(word.length <= maxWordSize, "result exceeded 5 letters");
});
it("should return one word with the length between 3 and 5 ", function () {
const minLengthSize = 3;
const maxLengthSize = 5;
const word = generate({
minLength: minLengthSize,
maxLength: maxLengthSize,
});
it('should return 5 words when called with the number 5', function () {
var words = randomWords(5);
assert.ok(words.length === 5, 'contains 5 elements');
assert.ok(
word.length >= minLengthSize && word.length <= maxLengthSize,
"result is not between the limit of 3 and 5"
);
});
it("should only return words with a minimum of 8 letters", function () {
const minWordSize = 8;
const words = generate({ exactly: 10000, minLength: minWordSize });
words.forEach((word) => {
assert.ok(word.length >= minWordSize, "result is less than 8 letters");
});
it('should return between 5 and 10 words when called with min: 5 and max: 10', function () {
var words = randomWords({min: 5, max: 10});
assert.ok((words.length >= 5) && (words.length <= 10));
});
it("should only return words with a maximum of 5 letters", function () {
const maxWordSize = 5;
const words = generate({ exactly: 10000, maxLength: maxWordSize });
words.forEach((word) => {
assert.ok(word.length <= maxWordSize, "result exceeded 5 letters");
});
it('returns result of variable length when called with min: 5 and max: 10', function () {
var lengths = {};
for (var i = 0; (i < 100); i++) {
var words = randomWords({min: 5, max: 10});
lengths[words.length] = true;
}
assert.ok(Object.keys(lengths).length > 1, 'result varies in length');
});
it("should only return words with the length between 3 and 5", function () {
const minLengthSize = 3;
const maxLengthSize = 5;
const words = generate({
exactly: 10000,
minLength: minLengthSize,
maxLength: maxLengthSize,
});
it('should return 5 space separated words when join is used with exactly: 5', function () {
var phrase = randomWords({exactly: 5, join: ' '});
assert.ok((typeof(phrase) === 'string'), 'result is a string');
assert.ok(phrase.match(/\S/), 'result contains text, not just spaces');
phrase = phrase.replace(/[\S]/g, '');
assert.ok(phrase.length === 4, 'result contains 4 spaces joining the 5 words');
words.forEach((word) => {
assert.ok(
word.length >= minLengthSize && word.length <= maxLengthSize,
"result is not between the limit of 3 and 5"
);
});
it('should return 5 concatenated words when join is used with an empty string and exactly: 5', function () {
var phrase = randomWords({exactly: 5, join: ''});
assert.ok((typeof(phrase) === 'string'), 'result is a string');
assert.ok(phrase.match(/\w/), 'result contains text, no spaces');
});
it("should only return words with length = 5", function () {
const wordSize = 5;
const words = generate({
exactly: 10000,
minLength: wordSize,
maxLength: wordSize,
});
it('should return 5 words when called with exactly: 5 and join: false', function () {
var words = randomWords({exactly: 5, join: false});
assert.ok(words.length === 5, 'contains 5 elements');
words.forEach((word) => {
assert.ok(word.length === wordSize, "word length is different from 5");
});
it('should return 5 words when called with exactly: 5 and join: null', function () {
var words = randomWords({exactly: 5, join: null});
assert.ok(words.length === 5, 'contains 5 elements');
});
it("maxLength larger than the longest word should not result in an endless loop", function () {
const wordSize = 100000;
const words = generate({
exactly: 1000,
maxLength: wordSize,
});
it('should only return words within the maxLength', function () {
var maxWordSize = 4
var words = randomWords({exactly: 10000, maxLength: maxWordSize});
words.forEach(word => {
assert.ok(word.length <= maxWordSize && word.length > 0, 'result is smaller than max size: ' + maxWordSize)
});
words.forEach((word) => {
assert.ok(word.length <= longestWordSize);
});
it('should return 5 space separated words for each string if wordsPerString is set to 5 and exactly > 1', function () {
var words = randomWords({exactly: 10, wordsPerString: 5});
words.forEach(string => {
stringSplitted = string.split(' ');
assert.ok(stringSplitted.length === 5, 'the i-th string contains 5 words');
});
});
it("minLength larger than the longest word should not result in an endless loop", function () {
const wordSize = 100000;
const words = generate({
exactly: 1000,
minLength: wordSize,
});
it('should reuturn 5 words separated by a separator for each string if wordsPerString > 1, separator is defined as a string and exactly > 1', function () {
const separator = '-';
var words = randomWords({exactly: 10, wordsPerString: 5, separator});
words.forEach(string => {
stringSplitted = string.split(separator);
assert.ok(typeof(separator) === 'string', 'separator is a string');
assert.ok(stringSplitted.length === 5, 'the i-th string contains 5 words');
});
words.forEach((word) => {
assert.ok(word.length <= longestWordSize);
});
it('should return styled strings if formatter is defined as a function that returns a string', function () {
formatter = (word) => word.toUpperCase();
assert.ok(typeof(formatter) === 'function', 'formatter is a function');
assert.ok(typeof(formatter('test')) === 'string', 'formatter returns a string');
var words = randomWords({exactly: 10, formatter});
words.forEach(word => {
assert.ok(word === word.toUpperCase(), 'word is formatted')
});
});
it("must return a word even without passing a number to minLength and maxLength", function () {
const word1 = generate({ minLength: undefined, maxLength: false });
const word2 = generate({ minLength: "string", maxLength: null });
assert.ok(
typeof word1 === "string" && typeof word2 === "string",
"result is not a string"
);
});
it("should return 5 space separated words for each string if wordsPerString is set to 5 and exactly > 1", function () {
const words = generate({ exactly: 10, wordsPerString: 5 });
words.forEach((string) => {
const stringSplitted = string.split(" ");
assert.ok(
stringSplitted.length === 5,
"the i-th string contains 5 words"
);
});
it('should return the same words if the same seed is used', function () {
const seed = 'seed1'
const exactly = 20;
const join = ' ';
});
it("should reuturn 5 words separated by a separator for each string if wordsPerString > 1, separator is defined as a string and exactly > 1", function () {
const separator = "-";
const words = generate({ exactly: 10, wordsPerString: 5, separator });
words.forEach((string) => {
const stringSplitted = string.split(separator);
assert.ok(typeof separator === "string", "separator is a string");
assert.ok(
stringSplitted.length === 5,
"the i-th string contains 5 words"
);
});
});
it("should return styled strings if formatter is defined as a function that returns a string", function () {
const formatter = (word) => word.toUpperCase();
assert.ok(typeof formatter === "function", "formatter is a function");
assert.ok(
typeof formatter("test") === "string",
"formatter returns a string"
);
const words = generate({ exactly: 10, formatter });
words.forEach((word) => {
assert.ok(word === word.toUpperCase(), "word is formatted");
});
});
it("should return the same words if the same seed is used", function () {
const seed = "seed1";
const exactly = 20;
const join = " ";
const words = randomWords({ seed, exactly, join });
const words2 = randomWords({ seed, exactly, join });
const words = generate({ seed, exactly, join });
const words2 = generate({ seed, exactly, join });
assert.ok(words == words2, 'words are the same')
});
it('should return the same number of words if the same seed is used', function () {
const seed = 'seed1'
const min = 1;
const max = 10;
assert.ok(words == words2, "words are the same");
});
it("should return the same number of words if the same seed is used", function () {
const seed = "seed1";
const min = 1;
const max = 10;
const words = randomWords({ seed, min, max });
const words2 = randomWords({ seed, min, max });
const words = generate({ seed, min, max });
const words2 = generate({ seed, min, max });
assert.ok(words.length == words2.length, 'number of words is the same')
});
it('should return different words if no seeds are provided', function () {
const exactly = 20;
const join = ' ';
assert.ok(words.length == words2.length, "number of words is the same");
});
it("should return different words if no seeds are provided", function () {
const exactly = 20;
const join = " ";
const words = randomWords({ exactly, join });
const words2 = randomWords({ exactly, join });
const words = generate({ exactly, join });
const words2 = generate({ exactly, join });
// with 1952 possible words, at least one word in 20 should be different
assert.ok(words != words2, 'words are different')
});
it('should return different words if different seeds are used', function () {
const exactly = 20;
// with 1952 possible words, at least one word in 20 should be different
assert.ok(words != words2, "words are different");
});
it("should return different words if different seeds are used", function () {
const exactly = 20;
const words = randomWords({ seed: 'seed1', exactly });
const words2 = randomWords({ seed: 'seed2', exactly });
const words = generate({ seed: "seed1", exactly });
const words2 = generate({ seed: "seed2", exactly });
// with these seeds, all words should be different
for (let i = 0; i < exactly; i++) {
assert.ok(words[i] != words2[i], 'words are different')
}
});
it('should return different number of words if different seeds are used', function () {
const min = 1;
const max = 10;
// with these seeds, all words should be different
for (let i = 0; i < exactly; i++) {
assert.ok(words[i] != words2[i], "words are different");
}
});
it("should return different number of words if different seeds are used", function () {
const min = 1;
const max = 10;
const words = randomWords({ seed: 'seed1', min, max });
const words2 = randomWords({ seed: 'seed2', min, max });
const words = generate({ seed: "seed1", min, max });
const words2 = generate({ seed: "seed2", min, max });
// with these seeds, the number of words should 5 and 3
assert.ok(words.length != words2.length, 'number of words is different')
});
// with these seeds, the number of words should 5 and 3
assert.ok(words.length != words2.length, "number of words is different");
});
});
describe("random-words : count", function () {
it("should return the correct count when no options are provided", function () {
const totalWords = count();
assert.ok(typeof totalWords === "number" && totalWords != 0 , "total number of words is a number and is not 0");
});
it("should return the correct count when minLength and maxLength options are provided", function () {
const options = { minLength: 5, maxLength: 8 };
const totalWords = count(options);
assert.ok(typeof totalWords === "number" && totalWords != 0 , "total number of words is a number and is not 0");
});
it("should return the correct count when only minLength option is provided", function () {
const options = { minLength: 8 };
const totalWords = count(options);
assert.ok(typeof totalWords === "number" && totalWords != 0 , "total number of words is a number and is not 0");
});
it("should return 0 when no words satisfy the length criteria", function () {
const options = { minLength: 30, maxLength: 35 };
const totalWords = count(options);
assert.ok(totalWords === 0 , "total number of words should be 0 when no words satisfy the length criteria");
});
it("should return 0 when minLength is greater than maxLength", function () {
const options = { minLength: 10, maxLength: 5 };
const totalWords = count(options);
assert.ok(totalWords === 0 , "total number of words should be 0 when minLength is greater than maxLength");
});
it("should return the default count when incorrect arguments are provided", function () {
const options = "Illegal arguments";
const totalWords = count(options);
assert.ok(typeof totalWords === "number" && totalWords != 0 , "total number of words is a number and is not 0");
});
it("should treat non-number minLength as default and return the correct count", function () {
const options = { minLength: "5" };
const totalWords = count(options);
assert.ok(typeof totalWords === "number" && totalWords != 0 , "total number of words is a number and is not 0");
});
it("should ignore other options and return the count based on minLength and maxLength only", function () {
const options = { minLength: 4, maxLength: 7, separator: "-", formatter: (word) => word.toUpperCase(), seed: "random" };
const totalWords = count(options);
assert.ok(typeof totalWords === "number" && totalWords != 0 , "total number of words is a number and is not 0");
});
it("should return 0 when negative minLength and maxLength are passed", function () {
const options = { minLength: -20, maxLength: -10 };
const totalWords = count(options);
assert.ok(totalWords === 0 , "total number of words should be 0 when no words satisfy the length criteria");
});
it("should return the correct count when minLength is -1 and maxLength is 10", function () {
const options = { minLength: -1, maxLength: 10 };
const totalWords = count(options);
assert.ok(typeof totalWords === "number" && totalWords != 0 , "total number of words is a number and is not 0");
});
})
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc