├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── package.json ├── src ├── boolean.js ├── color.js ├── distribution.js ├── float.js ├── index.js ├── integer.js ├── set.js └── string.js └── test └── test.js /.gitignore: -------------------------------------------------------------------------------- 1 | build/*.js 2 | node_modules 3 | stochator*.js 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src/* 2 | stochator.js 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License, version 2.0 2 | 1. Definitions 3 | 1.1. “Contributor” 4 | means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 5 | 6 | 1.2. “Contributor Version” 7 | means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. 8 | 9 | 1.3. “Contribution” 10 | means Covered Software of a particular Contributor. 11 | 12 | 1.4. “Covered Software” 13 | means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 14 | 15 | 1.5. “Incompatible With Secondary Licenses” 16 | means 17 | 18 | that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or 19 | 20 | that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 21 | 22 | 1.6. “Executable Form” 23 | means any form of the work other than Source Code Form. 24 | 25 | 1.7. “Larger Work” 26 | means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 27 | 28 | 1.8. “License” 29 | means this document. 30 | 31 | 1.9. “Licensable” 32 | means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 33 | 34 | 1.10. “Modifications” 35 | means any of the following: 36 | 37 | any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or 38 | 39 | any new file in Source Code Form that contains any Covered Software. 40 | 41 | 1.11. “Patent Claims” of a Contributor 42 | means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 43 | 44 | 1.12. “Secondary License” 45 | means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 46 | 47 | 1.13. “Source Code Form” 48 | means the form of the work preferred for making modifications. 49 | 50 | 1.14. “You” (or “Your”) 51 | means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 52 | 53 | 2. License Grants and Conditions 54 | 2.1. Grants 55 | Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: 56 | 57 | under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and 58 | 59 | under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 60 | 61 | 2.2. Effective Date 62 | The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 63 | 64 | 2.3. Limitations on Grant Scope 65 | The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: 66 | 67 | for any code that a Contributor has removed from Covered Software; or 68 | 69 | for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or 70 | 71 | under Patent Claims infringed by Covered Software in the absence of its Contributions. 72 | 73 | This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 74 | 75 | 2.4. Subsequent Licenses 76 | No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 77 | 78 | 2.5. Representation 79 | Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 80 | 81 | 2.6. Fair Use 82 | This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 83 | 84 | 2.7. Conditions 85 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 86 | 87 | 3. Responsibilities 88 | 3.1. Distribution of Source Form 89 | All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. 90 | 91 | 3.2. Distribution of Executable Form 92 | If You distribute Covered Software in Executable Form then: 93 | 94 | such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and 95 | 96 | You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. 97 | 98 | 3.3. Distribution of a Larger Work 99 | You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 100 | 101 | 3.4. Notices 102 | You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 103 | 104 | 3.5. Application of Additional Terms 105 | You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 106 | 107 | 4. Inability to Comply Due to Statute or Regulation 108 | If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 109 | 110 | 5. Termination 111 | 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 112 | 113 | 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 114 | 115 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. 116 | 117 | 6. Disclaimer of Warranty 118 | Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. 119 | 120 | 7. Limitation of Liability 121 | Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 122 | 123 | 8. Litigation 124 | Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. 125 | 126 | 9. Miscellaneous 127 | This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 128 | 129 | 10. Versions of the License 130 | 10.1. New Versions 131 | Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 132 | 133 | 10.2. Effect of New Versions 134 | You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 135 | 136 | 10.3. Modified Versions 137 | If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 138 | 139 | 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses 140 | If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. 141 | 142 | Exhibit A - Source Code Form License Notice 143 | This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 144 | 145 | If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. 146 | 147 | You may add additional accurate notices of copyright ownership. 148 | 149 | Exhibit B - “Incompatible With Secondary Licenses” Notice 150 | This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Download the latest compiled version of stochator.js (0.6): 2 | - [development](https://github.com/heydenberk/stochator/releases/download/0.6/stochator.js) (unminified, 60Kb). 3 | - [production](https://github.com/heydenberk/stochator/releases/download/0.6/stochator.min.js) (minified, 24Kb). 4 | 5 | # Stochator 6 | 7 | `Stochator` is a tiny library providing for creating a variety of random value generators. 8 | 9 | - [Floating-point decimals](#floating-point-decimals) 10 | - [Floats from an interval](#floats-from-an-interval) 11 | - [Floats from a normal distribution](#floats-from-a-normal-distribution) 12 | - [Integers](#integers) 13 | - [Booleans](#booleans) 14 | - [Multiple results](#multiple-results) 15 | - [From sets](#from-sets) 16 | - [From sets with weights](#from-sets-with-weights) 17 | - [From sets without replacement](#from-sets-without-replacement) 18 | - [From predefined sets](#from-predefined-sets) 19 | - [Strings](#strings) 20 | - [Mutators](#mutators) 21 | - [Multiple generators](#multiple-generators) 22 | - [Changelog](#changelog) 23 | 24 | To create a `Stochator` object, simply invoke the constructor and pass it an `options` object with a `kind` property. If not provided, kind is 'float'. 25 | 26 | Valid kinds include `float`, `integer`, `set`, `color`, `a-z` and `A-Z`. 27 | 28 | ## Floating-point decimals 29 | *New in 0.5: available as `Stochator.randomFloat(min, max, prng=Math.random)`* 30 | 31 | It's very easy generate a float between 0 and 1. 32 | 33 | ````js 34 | var generator = new Stochator({}); 35 | generator.next(); // 0.9854211050551385 36 | generator.next(); // 0.8784450970124453 37 | generator.next(); // 0.1592887439765036 38 | ```` 39 | 40 | This is not very exciting because it simply wraps the built-in `Math.random` method. 41 | 42 | 43 | ## Floats from an interval 44 | *New in 0.5: available as `Stochator.randomFloat(min, max, prng=Math.random)`* 45 | 46 | Specifying a min and a max allows us to create random numbers in the interval (min, max), not inclusive. 47 | 48 | ````js 49 | var radianGenerator = new Stochator({ 50 | min: 0, 51 | max: Math.PI * 2 52 | }); 53 | radianGenerator.next(); // 3.7084574239999655 54 | radianGenerator.next(); // 1.021138034566463 55 | radianGenerator.next(); // 4.012664264853087 56 | ```` 57 | 58 | ## Floats from a normal distribution 59 | *New in 0.5: available as: `Stochator.fromDistribution.normal(mean, stdev, min, max, prng=Math.random)`* 60 | 61 | We can also generate random floats from a normal distribution. Min and max are optional, and when provided will result in truncation of all results outside of [min, max]. 62 | 63 | ````js 64 | var testScores = new Stochator({ 65 | mean: 75, 66 | stdev: 14, 67 | min: 0, 68 | max: 100 69 | }); 70 | testScores.next(); // 59.437160028200125 71 | testScores.next(); // 80.18612670399554 72 | testScores.next(); // 75.81242027226946 73 | ```` 74 | 75 | ## Integers 76 | *New in 0.5: available as `Stochator.randomInteger(min, max, prng=Math.random)`* 77 | 78 | For integers, the interval [min, max] is inclusive. Notice that the optional argument `name` allows us to alias `next` to a more descriptive method name. 79 | 80 | ````js 81 | var die = new Stochator({ 82 | kind: "integer", 83 | min: 1, 84 | max: 6 85 | }, "roll"); 86 | die.roll(); // 6 87 | die.roll(); // 1 88 | die.roll(); // 2 89 | ```` 90 | 91 | *New in 0.6* 92 | *Available as `Stochator.randomByte(prng=Math.random)`* 93 | 94 | The special case of generating byte integers has its own shorthand. 95 | 96 | ```js 97 | Stochator.randomByte() // 186; 98 | ``` 99 | 100 | ## Booleans 101 | *New in 0.6* 102 | *Available as `Stochator.randomBoolean(prng=Math.random)`* 103 | 104 | Although trivally composable from other generators, randomBoolean is provided for convenience. 105 | 106 | ````js 107 | var bools = new Stochator({kind: "boolean"}); 108 | bools.next(); // false 109 | bools.next(); // true 110 | bools.next(); // true 111 | ```` 112 | 113 | ## Multiple results 114 | 115 | If the `next` method (or a method aliased to it) is passed an integer `n`, it will return an n-length array of results. Using the die instance from the previous example: 116 | 117 | ````js 118 | die.roll(1); // [5] 119 | die.roll(2); // [5, 3] 120 | die.roll(5); // [6, 3, 6, 6, 5] 121 | ```` 122 | 123 | 124 | ## From sets 125 | *New in 0.5: available as `Stochator.randomSetMember(values, prng=Math.random)`* 126 | 127 | We can generate random values from arbitary sets. 128 | 129 | ````js 130 | var dayGenerator = new Stochator({ 131 | kind: "set", 132 | values: ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] 133 | }); 134 | dayGenerator.next(); // friday 135 | dayGenerator.next(); // monday 136 | dayGenerator.next(); // monday 137 | ```` 138 | 139 | ## From sets with weights 140 | *New in 0.5: available as `Stochator.weightedRandomSetMember(values, weights, prng=Math.random)`* 141 | 142 | What if we favor the weekend? Well, we can pass `weights`, an array of the same length as `values` consisting of probabilities out of 1 that correspond to `values`. 143 | 144 | ````js 145 | var biasedDayGenerator = new Stochator({ 146 | kind: "set", 147 | values: ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"], 148 | weights: [0.1, 0.1, 0.1, 0.1, 0.1, 0.25, 0.25] 149 | }); 150 | biasedDayGenerator.next(); // thursday 151 | biasedDayGenerator.next(); // sunday 152 | biasedDayGenerator.next(); // saturday 153 | ```` 154 | 155 | ## From sets without replacement 156 | *New in 0.5: available as `Stochator.randomSetMemberWithoutReplacement(set, prng=Math.random)`* 157 | 158 | Passing a `replacement` property with a falsy value will result in each random 159 | value generation to be removed from the set. 160 | 161 | ````js 162 | var chores = new Stochator({ 163 | kind: "set", 164 | values: ["floors", "windows", "dishes"], 165 | replacement: false 166 | }); 167 | var myChore = chores.next(); // "windows" 168 | var yourChore = chores.next(); // "floors" 169 | var hisChore = chores.next(); // "dishes" 170 | var noOnesChore = chores.next(); // undefined 171 | ```` 172 | 173 | ## From predefined sets 174 | *New in 0.5: available as `Stochator.randomColor(prng=Math.random)`, `Stochator.randomLowercaseCharacter(prng=Math.random)` and `Stochator.randomUppercaseCharacter(prng=Math.random)`* 175 | 176 | At present, predefined sets include `"a-z"`, `"A-Z"` and `"color"`. 177 | 178 | ````js 179 | var colorGenerator = new Stochator({ 180 | kind: "color" 181 | }); 182 | colorGenerator.next(); // { red: 122, green: 200, blue: 121 } 183 | colorGenerator.next(); // { red: 129, green: 89, blue: 192 } 184 | colorGenerator.next(); // { red: 125, green: 211, blue: 152 } 185 | ```` 186 | 187 | Note that this example passes an integer argument `n` to `next` which causes 188 | the stochator to return an array with the result of `n` calls to the generator. 189 | 190 | ````js 191 | var characterGenerator = new Stochator({ 192 | kind: "a-z" 193 | }); 194 | characterGenerator.next(25).join(""); // "uktlbkgufzjiztatmqelawfez" 195 | characterGenerator.next(25).join(""); // "wdhygotehcfmrkjyuuovztxla" 196 | characterGenerator.next(25).join(""); // "mbjxkhflycpxgdrtyyyevasga" 197 | ```` 198 | 199 | ## Strings 200 | *New in 0.6* 201 | *Also available as: 202 | `Stochator.randomCharacterFromRange(range, prng=Math.random)` 203 | `Stochator.randomAsciiString(expression, ignoreCase, prng=Math.random)` 204 | `Stochator.randomUnicodeString(expression, ignoreCase, prng=Math.random)` 205 | `Stochator.randomAsciiCharacter(prng=Math.random)` 206 | `Stochator.randomLowercaseCharacter(prng=Math.random)` 207 | `Stochator.randomUnicodeCharacter(prng=Math.random)` 208 | `Stochator.randomUppercaseCharacter(prng=Math.random)`* 209 | 210 | For more flexibility than the pre-defined sets allow, we can use a regular expression. 211 | 212 | ```js 213 | var hexGenerator = new Stochator({ 214 | kind: "string", 215 | expression: "#[A-F0-9]{6}" 216 | }); 217 | hexGenerator.next(); // "#57A7BB" 218 | ``` 219 | 220 | Passing the `ignoreCase` argument with a value of `true` will cause characters in the a-z and A-Z ranges to be randomized in case. 221 | 222 | ```js 223 | var coolGreetingGenerator = new Stochator({ 224 | kind: "string", 225 | expression: "Hello, world", 226 | ignoreCase: true 227 | }); 228 | coolGreetingGenerator.next(); // "hELLo, WorlD" 229 | ``` 230 | 231 | `expression` can also be a true regular expression, in which case the trailing `i` flag will be honored. 232 | 233 | ```js 234 | var coolGreetingGenerator = new Stochator({ 235 | kind: "string", 236 | expression: /Hello, world/i, 237 | ignoreCase: true 238 | }); 239 | coolGreetingGenerator.next(); // "HELlO, WorLD" 240 | ``` 241 | 242 | All features supported by JavaScript regular expressions should work. 243 | 244 | ```js 245 | var fruitGenerator = new Stochator({ 246 | kind: "string", 247 | expression: "((Apples|Oranges|Pears)! ?){1,5}" 248 | }); 249 | fruitGenerator.next(); // "Oranges!Pears! Apples! " 250 | ``` 251 | 252 | By default, the resulting characters are limited to ASCII. If you want unicode, pass the property `unicode` with a value of `true`. 253 | 254 | ```js 255 | var unicodeGenerator = new Stochator({ 256 | kind: "string", 257 | expression: ".{10}", 258 | unicode: true 259 | }); 260 | unicodeGenerator.next(); // "貧㒐⮧Ꮜ�惜攤鎃๵켕" 261 | ``` 262 | 263 | To override the maximum length of an unbounded match (`*` or `{n,}`), provide `maxWildcard` as `true`. 264 | 265 | ```js 266 | var binaryGenerator = new Stochator({ 267 | kind: "string", 268 | expression: "Look at all this binary: ((0|1){256})", 269 | maxWildcard: 256 270 | }); 271 | binaryGenerator.next(); // "Look at all this binary: 1001011001010011100010101000011100010110010100100100000000110011010000000100000111111010110010100000010101001001100110011001111001111000111101000111010101011100010101101100001011110011110001101100001000001100101111110100001110100100000010111101111011111101" 272 | ``` 273 | 274 | Special thanks to [randexp.js](https://github.com/fent/randexp.js) for inspiring this feature and informing its approach! 275 | 276 | ## Mutators 277 | The constructor accepts an optional final argument which is passed the output 278 | of the random value generator. Its return value becomes the return value of 279 | next or its alias. To generate random boolean values, we can do: 280 | 281 | ````js 282 | var booleanGenerator = new Stochator({ 283 | kind: "integer", 284 | min: 0, 285 | max: 1 286 | }, Boolean); 287 | 288 | booleanGenerator.next(); // false 289 | booleanGenerator.next(); // true 290 | booleanGenerator.next(); // true 291 | ```` 292 | 293 | We can map the previously mentioned `radianGenerator` to the cosine of its values. 294 | 295 | ````js 296 | var radianSineGenerator = new Stochator({ 297 | min: 0, 298 | max: Math.PI * 2 299 | }, Math.cos); 300 | radianSineGenerator.next(); // -0.31173382958096524 301 | radianSineGenerator.next(); // -0.6424354006937544 302 | radianSineGenerator.next(); // 0.6475980728835664 303 | ```` 304 | 305 | Mutators remember their previous result and, at each generation, apply the results of a specified stochator to create a new result. 306 | 307 | _(This is functionally equivalent to a Markov chain.)_ 308 | 309 | ````js 310 | var drunkardsWalk = new Stochator({ 311 | kind: "integer", 312 | min: -1, 313 | max: 1 314 | }, function(a, b) { return a + b; }); 315 | 316 | drunkardsWalk.next(10); // [-1, -2, -2, -1, -1, -1, 0, 1, 1, 2] 317 | drunkardsWalk.next(10); // [3, 3, 3, 2, 1, 0, -1, 0, 0, 0] 318 | drunkardsWalk.next(10); // [0, 1, 0, -1, 0, 0, 1, 2, 1, 1] 319 | ```` 320 | 321 | Let's model a bank account's balance. How much money might you have after 10 years if you start with $1000, add $1000 every year, and get interest at a random rate between 1% and 5%? 322 | 323 | ````js 324 | var addInterest = function(interestRate, principal) { 325 | return (principal + 1000) * interestRate; 326 | }; 327 | var savingsAccountBalance = new Stochator({ 328 | kind: "float", 329 | min: 1.01, 330 | max: 1.05 331 | }, addInterest); 332 | 333 | savingsAccountBalance.setValue(1000); // Sets the initital value 334 | savingsAccountBalance.next(10); 335 | /* 336 | [ 337 | 2096.2402432970703, 338 | 3177.3792999428224, 339 | 4339.349049328612, 340 | 5441.863800747634, 341 | 6507.916293297546, 342 | 7669.519280743041, 343 | 9011.783840249629, 344 | 10225.82489660009, 345 | 11630.122217972781, 346 | 12782.667463879243 347 | ] 348 | */ 349 | ```` 350 | 351 | ## Multiple generators 352 | If the Stochator constructor is passed multiple configuration objects, `next` (or its alias) returns an array of each random generated value. 353 | 354 | To generate a random point, we might do: 355 | 356 | ````js 357 | var x = { kind: 'integer', min: 0, max: 480 }; 358 | var y = { kind: 'integer', min: 0, max: 360 }; 359 | var mutator = function(values) { 360 | return { 361 | x: values[0], 362 | y: values[1] 363 | }; 364 | }; 365 | var randomPoint = new Stochator(x, y, mutator); 366 | 367 | randomPoint.next(); // { x: 79, y: 65 } 368 | randomPoint.next(); // { x: 151, y: 283 } 369 | randomPoint.next(); // { x: 5, y: 253 } 370 | ```` 371 | 372 | ## Overriding the pseudo-random number generator 373 | *New in 0.4.* 374 | 375 | Add a `prng` function to the configuration object to set your own pseudo-random number generator. 376 | 377 | ````js 378 | var seedrandom = require('seedrandom'); 379 | new Stochator({ prng: seedrandom('STOCHATOR') }).next(); // Always 0.4045178783365678 380 | ```` 381 | 382 | ## Using a seed 383 | *New in 0.4.* 384 | 385 | Rather than requiring seedrandom and passing a PRNG with a seed (as above), you can simply provide a seed value. 386 | ````js 387 | new Stochator({ seed: 'STOCHATOR' }).next(); // Still always 0.4045178783365678 388 | ```` 389 | 390 | ## Changelog 391 | ### 0.6 392 | [Stochator now supports a `kind` of `string`](#strings), which supports generation of pseudo-random strings that satisfy 393 | provided regular expressions. 394 | ### 0.5 395 | The entire project has been rewritten to use ES6 features, with translation handled by babel and browserify. 396 | In addition, `Stochator` has been supplemented with static methods to facilitate single-use value generators. 397 | ### 0.4 398 | `prng` can be provided on a config object to override `Math.random` as the pseudo-random number generator. `seed` can be provided to seed the PRNG with an initial value. If both are provided, the PRNG will be the function returned by calling `config.prng(config.seed)`; if just `seed` is provided, the PRNG will default to [seedrandom](https://github.com/davidbau/seedrandom) rather than `Math.random`. 399 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "browserify": { 3 | "transform": [ 4 | [ 5 | "babelify", 6 | { 7 | "stage": 0 8 | } 9 | ] 10 | ] 11 | }, 12 | "bugs": "http://github.com/heydenberk/stochator/issues", 13 | "description": "A tiny library providing for creating a variety of random value generators.", 14 | "devDependencies": { 15 | "babel": "^5.8.23", 16 | "babelify": "^6.3.0", 17 | "browserify": "^11.0.1", 18 | "lodash": ">=3.0", 19 | "mocha": "^2.3.1", 20 | "uglify-js": "^2.4.24", 21 | "uglifyify": "^3.0.1" 22 | }, 23 | "dependencies": { 24 | "discontinuous-range": "1.0.0", 25 | "lodash.identity": "^3.0", 26 | "lodash.isfunction": "^3.0", 27 | "lodash.isregexp": "^3.0", 28 | "lodash.isstring": "^3.0", 29 | "lodash.range": "^3.0", 30 | "ret": "0.1.10", 31 | "seedrandom": "^2.4.2" 32 | }, 33 | "homepage": "https://github.com/heydenberk/stochator", 34 | "keywords": [ 35 | "random", 36 | "numbers", 37 | "values", 38 | "color", 39 | "string", 40 | "integer", 41 | "array", 42 | "shuffle", 43 | "set", 44 | "markov", 45 | "chain", 46 | "generator", 47 | "prng", 48 | "normal", 49 | "distribution" 50 | ], 51 | "license": "MPL-2.0", 52 | "main": "build/index.js", 53 | "name": "stochator", 54 | "repository": { 55 | "type": "git", 56 | "url": "https://github.com/heydenberk/stochator" 57 | }, 58 | "scripts": { 59 | "build-browser": "npm install && browserify --no-builtins src/index.js > stochator.js", 60 | "build-browser-min": "npm install && browserify -g uglifyify --no-builtins src/index.js | uglifyjs -c > stochator.min.js", 61 | "build": "babel src/ --out-dir=build --stage=0", 62 | "clean": "rm -rf build/ node_modules/", 63 | "prepublish": "npm run build", 64 | "test": "mocha" 65 | }, 66 | "version": "0.6.2" 67 | } 68 | -------------------------------------------------------------------------------- /src/boolean.js: -------------------------------------------------------------------------------- 1 | import integer from "./integer"; 2 | 3 | const random = (prng=Math.random) => 4 | Boolean(integer.boundedRandom(0, 1, prng)); 5 | 6 | export default {random}; -------------------------------------------------------------------------------- /src/color.js: -------------------------------------------------------------------------------- 1 | import integer from "./integer"; 2 | 3 | const randomRgb = (prng=Math.random) => { 4 | return { 5 | red: integer.randomByte(prng), 6 | green: integer.randomByte(prng), 7 | blue: integer.randomByte(prng) 8 | }; 9 | }; 10 | 11 | export default {randomRgb}; 12 | -------------------------------------------------------------------------------- /src/distribution.js: -------------------------------------------------------------------------------- 1 | import float from "./float"; 2 | 3 | const inverseNormalCumulativeDistribution = (probability) => { 4 | const high = probability > 0.97575; 5 | const low = probability < 0.02425; 6 | let numCoefficients, denomCoeffcients, numMaxExponent, denomMaxExponent, coefficient, base; 7 | 8 | if (low || high) { 9 | numCoefficients = [ 10 | -7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, 11 | -2.549732539343734, 4.374664141464968 12 | ]; 13 | denomCoeffcients = [ 14 | 7.784695709041462e-3, 3.224671290700398e-1, 15 | 2.445134137142996, 3.754408661907416 16 | ]; 17 | 18 | [numMaxExponent, denomMaxExponent] = [5, 4]; 19 | coefficient = low ? 1 : -1; 20 | base = Math.sqrt( 21 | -2 * Math.log(low ? probability : 1 - probability) 22 | ); 23 | } else { 24 | numCoefficients = [ 25 | -3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 26 | 1.383577518672690e2, -3.066479806614716e1, 2.506628277459239 27 | ]; 28 | denomCoeffcients = [ 29 | -5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 30 | 6.680131188771972e1, -1.328068155288572e1 31 | ]; 32 | 33 | [numMaxExponent, denomMaxExponent] = [5, 5]; 34 | coefficient = probability - 0.5; 35 | base = Math.pow(coefficient, 2); 36 | } 37 | 38 | const mapMaxExp = (maxExp) => { 39 | return (value, index) => value * Math.pow(base, maxExp - index); 40 | }; 41 | 42 | const sum = (arr) => arr.reduce((result, value) => result + value, 0); 43 | 44 | const numerator = sum(numCoefficients.map(mapMaxExp(numMaxExponent))); 45 | const denominator = sum(denomCoeffcients.map(mapMaxExp(denomMaxExponent))) + 1; 46 | 47 | return coefficient * numerator / denominator; 48 | }; 49 | 50 | const randomNormallyDistributedFloat = (mean, stdev, min, max, prng=Math.random) => { 51 | const seed = float.boundedRandom(0, 1, prng); 52 | const result = inverseNormalCumulativeDistribution(seed) * stdev + mean; 53 | return min != null && max != null ? 54 | Math.min(max, Math.max(min, result)) : result; 55 | }; 56 | 57 | export default {randomNormallyDistributedFloat}; -------------------------------------------------------------------------------- /src/float.js: -------------------------------------------------------------------------------- 1 | const boundedRandom = (min = 0, max = 1, prng=Math.random) => { 2 | const spread = max - min; 3 | return prng() * spread + min; 4 | }; 5 | 6 | export default {boundedRandom}; 7 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import identity from "lodash.identity"; 2 | import isFunction from "lodash.isfunction"; 3 | import isRegExp from "lodash.isregexp"; 4 | import isString from "lodash.isstring"; 5 | import range from "lodash.range"; 6 | import boolean from "./boolean"; 7 | import color from "./color"; 8 | import distribution from "./distribution"; 9 | import float from "./float"; 10 | import integer from "./integer"; 11 | import seedrandom from "seedrandom"; 12 | import set from "./set"; 13 | import string from "./string"; 14 | 15 | const booleanGenerator = ({prng}) => () => boolean.random(prng); 16 | 17 | const colorGenerator = ({prng}) => () => color.randomRgb(prng); 18 | 19 | const floatGenerator = ({min, max, mean, prng, stdev}) => { 20 | if (mean && stdev) { 21 | return () => distribution.randomNormallyDistributedFloat(mean, stdev, min, max, prng); 22 | } else { 23 | return () => float.boundedRandom(min, max, prng); 24 | } 25 | }; 26 | 27 | const integerGenerator = ({min, max, prng}) => { 28 | return () => integer.boundedRandom(min, max, prng); 29 | }; 30 | 31 | const setGenerator = ({values, prng, replacement=true, shuffle=false, weights=null}) => { 32 | if (!values || !values.length) { 33 | throw Error("Must provide a 'values' array for a set generator.") 34 | } 35 | 36 | if (shuffle) { 37 | return () => set.shuffle(values, prng); 38 | } else if (replacement) { 39 | if (weights) { 40 | return () => set.weightedRandomMember(values, weights, prng); 41 | } else { 42 | return () => set.randomMember(values, prng); 43 | } 44 | } else { 45 | return () => set.randomMemberWithoutReplacement(values, prng); 46 | } 47 | }; 48 | 49 | const stringGenerator = ({kind, expression=`[${kind}]`, ignoreCase=false, maxWildcard=100, prng, unicode=false}) => { 50 | const isRe = isRegExp(expression); 51 | const exprSource = isRe ? expression.source : expression; 52 | const options = { 53 | ignoreCase: ignoreCase || (isRe && expression.ignoreCase), 54 | maxWildcard, 55 | prng 56 | }; 57 | return string.generateString(unicode, exprSource, options); 58 | }; 59 | 60 | const KIND_GENERATORS = { 61 | "boolean": booleanGenerator, 62 | "float": floatGenerator, 63 | "integer": integerGenerator, 64 | "set": setGenerator, 65 | "color": colorGenerator, 66 | "rgb": colorGenerator, 67 | "string": stringGenerator, 68 | "a-z": stringGenerator, 69 | "A-Z": stringGenerator 70 | }; 71 | 72 | const VALID_KINDS = Object.keys(KIND_GENERATORS); 73 | 74 | const validateKind = (kind) => { 75 | if (VALID_KINDS.indexOf(kind) !== -1) { 76 | return true; 77 | } 78 | throw Error(`${kind} is in invalid kind. Valid kinds include: 79 | ${VALID_KINDS.join(', ')}`); 80 | }; 81 | 82 | const getConfigWithDefaults = (rawConfig) => { 83 | return {kind: "float", ...rawConfig, prng: getPrng(rawConfig)}; 84 | }; 85 | 86 | const createGenerator = (rawConfig) => { 87 | const config = getConfigWithDefaults(rawConfig); 88 | validateKind(config.kind); 89 | return KIND_GENERATORS[config.kind](config); 90 | }; 91 | 92 | const getNextValueGenerator = (configs) => { 93 | configs[0] = configs[0] ? configs[0] : {}; 94 | const generators = [for (config of configs) createGenerator(config)]; 95 | if (generators.length === 1) { 96 | return () => generators[0](); 97 | } else { 98 | return () => [for (generator of generators) generator()]; 99 | } 100 | }; 101 | 102 | const getPrng = ({seed, prng}) => { 103 | const defaultPrng = seed ? seedrandom : Math.random; 104 | const basePrng = prng ? prng : defaultPrng; 105 | return seed ? basePrng(seed) : basePrng; 106 | }; 107 | 108 | const parseArgs = (args) => { 109 | const defaults = {configs: [], mutator: null, name: null}; 110 | return args.reduce((result, arg) => { 111 | if (result.mutator || isString(arg)) { 112 | result.name = arg; 113 | } else if (isFunction(arg)) { 114 | result.mutator = arg; 115 | } else { 116 | result.configs.push(arg); 117 | } 118 | return result; 119 | }, defaults); 120 | }; 121 | 122 | 123 | export default class Stochator { 124 | 125 | VERSION = "0.6" 126 | 127 | static fromDistribution = { 128 | normal: distribution.randomNormallyDistributedFloat 129 | }; 130 | 131 | static randomAsciiCharacter = string.randomAsciiCharacter; 132 | 133 | static randomAsciiString = string.randomAsciiString; 134 | 135 | static randomBoolean = boolean.random; 136 | 137 | static randomByte = integer.randomByte; 138 | 139 | static randomCharacterFromRange = string.randomCharacterFromRange; 140 | 141 | static randomColor = color.randomRgb; 142 | 143 | static randomFloat = float.boundedRandom; 144 | 145 | static randomInteger = integer.boundedRandom; 146 | 147 | static randomLowercaseCharacter = string.randomLowercaseCharacter; 148 | 149 | static randomSetMember = set.randomMember; 150 | 151 | static randomSetMemberWithoutReplacement = set.randomMemberWithoutReplacement; 152 | 153 | static randomUnicodeCharacter = string.randomUnicodeCharacter; 154 | 155 | static randomUnicodeString = string.randomUnicodeString; 156 | 157 | static randomUppercaseCharacter = string.randomUppercaseCharacter; 158 | 159 | static shuffleSet = set.shuffleSet; 160 | 161 | static weightedRandomSetMember = set.weightedRandomMember; 162 | 163 | 164 | constructor(...args) { 165 | const {configs, mutator, name} = parseArgs(args); 166 | 167 | // If the mutator is provided, override the default identity func. 168 | this.mutate = mutator ? 169 | (nextValue) => mutator(nextValue, this.getValue()) : identity; 170 | 171 | // Transform the configs to a func to get the next value. 172 | const getNext = getNextValueGenerator(configs); 173 | 174 | // Assign `name` to the next mutated value(s), after `times` iterations. 175 | // If `times` is 1, just return the value, otherwise return an array. 176 | this.next = (times=1) => { 177 | const values = [ 178 | for (time of range(1, times + 1)) 179 | this.setValue(this.mutate(getNext())) 180 | ]; 181 | return times == 1 ? values[0] : values; 182 | }; 183 | 184 | if (name) { 185 | this[name] = (...args) => this.next(...args); 186 | } 187 | } 188 | 189 | getValue() { 190 | return this._value; 191 | } 192 | 193 | setValue(value) { 194 | this._value = value; 195 | return this._value; 196 | } 197 | 198 | toString() { 199 | return "[object Stochator]"; 200 | } 201 | 202 | _value = 0 203 | } 204 | 205 | if (global) { 206 | global.Stochator = Stochator; 207 | } 208 | -------------------------------------------------------------------------------- /src/integer.js: -------------------------------------------------------------------------------- 1 | const boundedRandom = (min = 0, max = 1, prng=Math.random) => { 2 | const spread = 1 + max - min; 3 | return Math.floor(prng() * spread) + min; 4 | }; 5 | 6 | const randomByte = (prng=Math.random) => { 7 | return boundedRandom(0, 255, prng); 8 | }; 9 | 10 | export default {boundedRandom, randomByte}; 11 | -------------------------------------------------------------------------------- /src/set.js: -------------------------------------------------------------------------------- 1 | import float from "./float"; 2 | import integer from "./integer"; 3 | 4 | const randomMember = (values, prng=Math.random) => { 5 | const max = values.length - 1; 6 | return values[integer.boundedRandom(0, max, prng)]; 7 | }; 8 | 9 | const randomMemberWithoutReplacement = (values, prng=Math.random) => { 10 | if (values.length > 0) { 11 | const index = integer.boundedRandom(0, values.length - 1, prng); 12 | const value = values[index]; 13 | values.splice(index, 1); 14 | return value; 15 | } 16 | }; 17 | 18 | const weightedRandomMember = (values, weights, prng=Math.random) => { 19 | let [member, weightSum, threshold] = [undefined, 0, float.boundedRandom(0, 1, prng)]; 20 | values.forEach((value, index) => { 21 | if (member) { 22 | return; 23 | } 24 | const weight = weights[index]; 25 | if (threshold <= weightSum + weight && threshold >= weightSum) { 26 | member = value; 27 | } 28 | weightSum += weight; 29 | }); 30 | 31 | return member; 32 | }; 33 | 34 | const shuffle = (values, prng=Math.random) => { 35 | let valuesRef = [...values]; 36 | for (index of range(0, valuesRef.length)) { 37 | randomIndex = integer.boundedRandom(0, index, prng); 38 | 39 | tmp = valuesRef[index]; 40 | valuesRef[index] = valuesRef[randomIndex]; 41 | valuesRef[randomIndex] = tmp; 42 | } 43 | return valuesRef; 44 | }; 45 | 46 | export default { 47 | randomMember, 48 | randomMemberWithoutReplacement, 49 | weightedRandomMember, 50 | shuffle 51 | }; 52 | -------------------------------------------------------------------------------- /src/string.js: -------------------------------------------------------------------------------- 1 | import boolean from "./boolean"; 2 | import integer from "./integer"; 3 | import set from "./set"; 4 | 5 | import ret from "ret"; 6 | import DRange from "discontinuous-range"; 7 | import _range from "lodash.range"; 8 | 9 | const LOWERCASE_RANGE = [97, 122]; 10 | 11 | const UPPERCASE_RANGE = [65, 90]; 12 | 13 | const ASCII_RANGE = [32, 126]; 14 | 15 | const UNICODE_RANGE = [0, 65535]; 16 | 17 | const AsciiDRange = DRange(...ASCII_RANGE); 18 | 19 | const UnicodeDRange = DRange(...UNICODE_RANGE); 20 | 21 | const inRange = ([min, max], n) => n >= min && n <= max; 22 | 23 | const changeCase = (code) => { 24 | const lowercase = inRange(LOWERCASE_RANGE, code); 25 | const uppercase = inRange(UPPERCASE_RANGE, code); 26 | return lowercase || uppercase ? code + (lowercase ? -32 : 32) : code; 27 | }; 28 | 29 | const createChar = (code, ignoreCase, prng) => 30 | code === null ? '' : String.fromCharCode( 31 | ignoreCase && boolean.random(prng) ? changeCase(code) : code); 32 | 33 | const expandCharacter = ({value}) => DRange(value); 34 | 35 | const expandRange = ({from, to}) => DRange(from, to); 36 | 37 | const expandSet = (token, range) => { 38 | let drange = DRange(); 39 | let setRanges = token.set.map((code) => expand(code, range)); 40 | setRanges.forEach((setRange) => drange.add(setRange)); 41 | return token.not ? range.clone().subtract(drange) : drange; 42 | }; 43 | 44 | const expanders = { 45 | [ret.types.SET]: expandSet, 46 | [ret.types.RANGE]: expandRange, 47 | [ret.types.CHAR]: expandCharacter 48 | }; 49 | 50 | const expand = (token, ...args) => expanders[token.type](token, ...args); 51 | 52 | // These generators accept a token and the options object and return a character 53 | // code. 54 | 55 | const generateCharFromSet = (token, {range, prng}) => { 56 | const set = expand(token, range); 57 | return set.index(integer.boundedRandom(0, set.length - 1, prng)); 58 | }; 59 | 60 | const generateCharFromRange = ({from, to}, {prng}) => 61 | integer.boundedRandom(from, to, prng); 62 | 63 | const generateChar = ({value}) => value; 64 | 65 | const createCharGenerator = (func) => 66 | (token, _, {range, ignoreCase, prng}) => 67 | createChar(func(token, {range, ignoreCase, prng}), ignoreCase, prng); 68 | 69 | // These generators accept a token, the groups and the options and return a 70 | // sequence of tokens, which are then in turn passed to generator functions. 71 | 72 | const generateFromGroup = ({notFollowedBy, options, stack}, _, {prng}) => 73 | notFollowedBy ? [] : options ? set.randomMember(options, prng) : stack; 74 | 75 | const generateRepeat = (token, _, options) => { 76 | const max = token.max === Infinity ? token.min + options.max : token.max; 77 | return _range(integer.boundedRandom(token.min, max, options.prng)) 78 | .map(() => token.value); 79 | }; 80 | 81 | const createSequenceGenerator = (func) => 82 | (token, groups, options) => 83 | func(token, groups, options) 84 | .map((value) => generateFromToken(value, groups, options)).join(''); 85 | 86 | // Generator dispatch table based upon the token type. 87 | 88 | const generators = { 89 | [ret.types.ROOT]: createSequenceGenerator(generateFromGroup), 90 | [ret.types.GROUP]: createSequenceGenerator(generateFromGroup), 91 | [ret.types.POSITION]: () => '', 92 | [ret.types.REPETITION]: createSequenceGenerator(generateRepeat), 93 | [ret.types.REFERENCE]: ({value}, groups) => groups[value - 1], 94 | [ret.types.CHAR]: createCharGenerator(generateChar), 95 | [ret.types.SET]: createCharGenerator(generateCharFromSet), 96 | [ret.types.RANGE]: createCharGenerator(generateCharFromRange) 97 | }; 98 | 99 | const generateFromToken = (token, groups, options) => { 100 | const result = generators[token.type](token, groups, options); 101 | if (token.type === ret.types.GROUP && token.remember) { 102 | groups.push(result); 103 | } 104 | return result; 105 | }; 106 | 107 | const generateStringFromRange = (range, expression, options) => 108 | () => generateFromToken(ret(expression), [], {range, ...options}); 109 | 110 | // Exported public functions. 111 | 112 | const generateCharacterFromRange = ([min, max], {prng}) => 113 | generateStringFromRange(DRange(min, max), '.', {prng}); 114 | 115 | const generateString = (unicode, expression, options) => 116 | generateStringFromRange( 117 | unicode ? UnicodeDRange : AsciiDRange, expression, options); 118 | 119 | const randomCharacterFromRange = (range, prng=Math.random) => 120 | generateCharacterFromRange(range, {prng})(); 121 | 122 | const randomAsciiString = (expression, ignoreCase, prng=Math.random) => 123 | generateStringFromRange(AsciiDRange, expression, {ignoreCase, prng}); 124 | 125 | const randomUnicodeString = (expression, ignoreCase, prng=Math.random) => 126 | generateStringFromRange(UnicodeDRange, expression, {ignoreCase, prng}); 127 | 128 | const randomAsciiCharacter = (prng=Math.random) => 129 | generateCharacterFromRange(ASCII_RANGE, {prng})(); 130 | 131 | const randomLowercaseCharacter = (prng=Math.random) => 132 | generateCharacterFromRange(LOWERCASE_RANGE, {prng})(); 133 | 134 | const randomUnicodeCharacter = (prng=Math.random) => 135 | generateCharacterFromRange(UNICODE_RANGE, {prng})(); 136 | 137 | const randomUppercaseCharacter = (prng=Math.random) => 138 | generateCharacterFromRange(UPPERCASE_RANGE, {prng})(); 139 | 140 | export default { 141 | generateString, 142 | randomCharacterFromRange, 143 | randomAsciiString, 144 | randomUnicodeString, 145 | randomAsciiCharacter, 146 | randomLowercaseCharacter, 147 | randomUnicodeCharacter, 148 | randomUppercaseCharacter 149 | }; 150 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | var _ = require('lodash'); 2 | var assert = require('assert'); 3 | var seedrandom = require('seedrandom'); 4 | var Stochator = require('../build'); 5 | 6 | var getPrng = function() { 7 | return seedrandom('STOCHATOR'); 8 | }; 9 | 10 | describe('Stochator (with seed STOCHATOR)', function() { 11 | 12 | it('should fail with an invalid kind', function() { 13 | assert.throws(function() { 14 | return new Stochator({kind: 'GARBAGE'}).next(); 15 | }); 16 | }); 17 | 18 | describe('the floating-point number generator', function() { 19 | 20 | it('should return a float between 0 and 1', function() { 21 | var result1 = new Stochator({ 22 | seed: 'STOCHATOR' 23 | }).next(); 24 | var result2 = Stochator.randomFloat(0, 1, getPrng()); 25 | 26 | assert.equal(result1, 0.4045178783365678); 27 | assert.equal(result2, 0.4045178783365678); 28 | }); 29 | 30 | it('should return a float between given bounds', function() { 31 | var result1 = new Stochator({ 32 | min: 0, 33 | max: Math.PI * 2, 34 | seed: 'STOCHATOR' 35 | }).next(); 36 | var result2 = Stochator.randomFloat(0, Math.PI * 2, getPrng()); 37 | 38 | assert.equal(result1, 2.5416607896557823); 39 | assert.equal(result2, 2.5416607896557823); 40 | }); 41 | 42 | it('should return a number from a normal distribution', function() { 43 | var result1 = new Stochator({ 44 | mean: 75, 45 | stdev: 14, 46 | min: 0, 47 | max: 100, 48 | seed: 'STOCHATOR' 49 | }).next(); 50 | var result2 = Stochator.fromDistribution.normal(75, 14, 0, 100, getPrng()); 51 | 52 | assert.equal(result1, 71.61661782743502); 53 | assert.equal(result2, 71.61661782743502); 54 | }); 55 | }); 56 | 57 | describe('the integer generator', function() { 58 | 59 | it('should return an integer between given bounds when "roll" is called', function() { 60 | var result1 = new Stochator({ 61 | kind: "integer", 62 | min: 1, 63 | max: 6, 64 | seed: "STOCHATOR" 65 | }, "roll").roll(); 66 | var result2 = Stochator.randomInteger(1, 6, getPrng()); 67 | 68 | assert.equal(result1, 3); 69 | assert.equal(result2, 3); 70 | }); 71 | 72 | it('should return an array of six integers between given bounds when "roll" is called', function() { 73 | var result1 = new Stochator({ 74 | kind: "integer", 75 | min: 1, 76 | max: 6, 77 | seed: "STOCHATOR" 78 | }, "roll").roll(5); 79 | 80 | var prng = getPrng(); 81 | var result2 = _.range(5).map(function() { 82 | return Stochator.randomInteger(1, 6, prng); 83 | }); 84 | 85 | assert.deepEqual(result1, [3, 6, 5, 1, 4]); 86 | assert.deepEqual(result2, [3, 6, 5, 1, 4]); 87 | }); 88 | 89 | }); 90 | 91 | describe('the boolean generator', function() { 92 | 93 | it('should return a random boolean value', function() { 94 | var result1 = new Stochator({kind: "boolean", seed: "STOCHATOR"}).next(); 95 | var result2 = Stochator.randomBoolean(getPrng()); 96 | 97 | assert.equal(result1, false); 98 | assert.equal(result2, false); 99 | }); 100 | 101 | }); 102 | 103 | describe('the set generator', function() { 104 | 105 | it('should return an item from a given array', function() { 106 | var result1 = new Stochator({ 107 | kind: "set", 108 | values: ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"], 109 | seed: "STOCHATOR" 110 | }).next(); 111 | var result2 = Stochator.randomSetMember( 112 | ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"], 113 | getPrng()); 114 | 115 | assert.equal(result1, 'wednesday'); 116 | assert.equal(result2, 'wednesday'); 117 | }); 118 | 119 | it("should return 7 items from an array with replacement according to given weights", function() { 120 | var result1 = new Stochator({ 121 | kind: "set", 122 | values: ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"], 123 | weights: [0.1, 0.1, 0.1, 0.1, 0.1, 0.25, 0.25], 124 | seed: 'STOCHATOR' 125 | }).next(7); 126 | 127 | var prng = getPrng(); 128 | var result2 = _.range(7).map(function() { 129 | return Stochator.weightedRandomSetMember( 130 | ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"], 131 | [0.1, 0.1, 0.1, 0.1, 0.1, 0.25, 0.25], 132 | prng 133 | ); 134 | }); 135 | 136 | assert.deepEqual(result1, ['friday', 'sunday', 'sunday', 'monday', 'saturday', 'monday', 'saturday']); 137 | assert.deepEqual(result2, ['friday', 'sunday', 'sunday', 'monday', 'saturday', 'monday', 'saturday']); 138 | }); 139 | 140 | it("should return 4 items from a set of 3 without replacement with a final item of undefined", function() { 141 | var result1 = new Stochator({ 142 | kind: "set", 143 | values: ["floors", "windows", "dishes"], 144 | replacement: false, 145 | seed: 'STOCHATOR' 146 | }).next(4); 147 | 148 | var prng = getPrng(); 149 | var set = ["floors", "windows", "dishes"]; 150 | var result2 = _.range(4).map(function() { 151 | return Stochator.randomSetMemberWithoutReplacement(set, prng); 152 | }); 153 | 154 | assert.deepEqual(result1, ['windows', 'dishes', 'floors', undefined]); 155 | assert.deepEqual(result2, ['windows', 'dishes', 'floors', undefined]); 156 | }); 157 | 158 | }); 159 | 160 | describe('the color generator', function() { 161 | 162 | it("should return an object with red, green and blue values", function() { 163 | var result1 = new Stochator({ 164 | kind: "color", 165 | seed: 'STOCHATOR' 166 | }).next(); 167 | var result2 = Stochator.randomColor(getPrng()); 168 | 169 | assert.deepEqual(result1, { red: 103, green: 244, blue: 192 }); 170 | assert.deepEqual(result2, { red: 103, green: 244, blue: 192 }); 171 | }); 172 | 173 | }); 174 | 175 | describe('the lowercase string generator', function() { 176 | 177 | it("should return 25 lowercase characters", function() { 178 | var result1 = new Stochator({ 179 | kind: "a-z", 180 | seed: 'STOCHATOR' 181 | }).next(25).join(''); 182 | 183 | var prng = getPrng(); 184 | var result2 = _.range(25).map(function() { 185 | return Stochator.randomLowercaseCharacter(prng); 186 | }).join(''); 187 | 188 | assert.equal(result1, 'kytapcrgjzwlmbbgxaeqlyspr'); 189 | assert.equal(result2, 'kytapcrgjzwlmbbgxaeqlyspr'); 190 | }); 191 | 192 | }); 193 | 194 | describe('the string generator', function() { 195 | 196 | it("should return 36 alphanumeric characters", function() { 197 | var result = new Stochator({ 198 | kind: "string", 199 | expression: "[a-zA-Z0-9]{36}", 200 | prng: getPrng() 201 | }).next(); 202 | 203 | assert.equal(result, '7UbLfPow91BEddp4akNC7SLP4F3SxPj8bb6f'); 204 | }); 205 | 206 | it("should randomize the case when ignoreCase is true", function() { 207 | var result = new Stochator({ 208 | kind: "string", 209 | expression: "Stochator", 210 | ignoreCase: true, 211 | prng: getPrng() 212 | }).next(); 213 | 214 | assert.equal(result, 'STOcHaTor'); 215 | }); 216 | 217 | it("should randomize the case when the i flag is set on a RegExp", function() { 218 | var result = new Stochator({ 219 | kind: "string", 220 | expression: /Stochator/i, 221 | prng: getPrng() 222 | }).next(); 223 | 224 | assert.equal(result, 'STOcHaTor'); 225 | }); 226 | 227 | it("should generate values from within groups", function() { 228 | var result = new Stochator({ 229 | kind: "string", 230 | expression: "Hello, (world|Stochator)!", 231 | prng: getPrng() 232 | }).next(); 233 | 234 | assert.equal(result, 'Hello, world!'); 235 | }); 236 | 237 | it("should generate values that don't match negated groups", function() { 238 | var result = new Stochator({ 239 | kind: "string", 240 | expression: "[^\\w]{10}", 241 | prng: getPrng() 242 | }).next(); 243 | 244 | assert.equal(result, '}\\ ="?\'+~`'); 245 | }); 246 | 247 | it("should generate values from within groups and with back-references", function() { 248 | var result = new Stochator({ 249 | kind: "string", 250 | expression: "Hello, (world|Stochator)! You're a great \\1!", 251 | prng: getPrng() 252 | }).next(); 253 | 254 | assert.equal(result, "Hello, world! You're a great world!"); 255 | }); 256 | 257 | it("should generate values with multiple out-of-order back-references", function() { 258 | var result = new Stochator({ 259 | kind: "string", 260 | expression: "Hello, (Alice|Bob)\\. Hello (Carol|Dan)\\. \\2, meet \\1\\. \\1, meet \\2\\.", 261 | prng: getPrng() 262 | }).next(); 263 | 264 | assert.equal(result, "Hello, Alice. Hello Dan. Dan, meet Alice. Alice, meet Dan."); 265 | }); 266 | 267 | it("should generate values that match positive lookaheads", function() { 268 | var result = new Stochator({ 269 | kind: "string", 270 | expression: "Alli(?=gators|son)", 271 | prng: getPrng() 272 | }).next(); 273 | 274 | assert.equal(result, "Alligators"); 275 | }); 276 | 277 | it("should generate values that match negative lookaheads", function() { 278 | var result = new Stochator({ 279 | kind: "string", 280 | expression: "Alli(?!son|gators)ance", 281 | prng: getPrng() 282 | }).next(); 283 | 284 | assert.equal(result, "Alliance"); 285 | }); 286 | 287 | it("should generate values from repeated groups", function() { 288 | var result = new Stochator({ 289 | kind: "string", 290 | expression: "My favorite color is #([0-9A-F]{2}){3}", 291 | prng: getPrng() 292 | }).next(); 293 | 294 | assert.equal(result, "My favorite color is #C01A5F"); 295 | }); 296 | 297 | it("should generate unicode strings when specified", function() { 298 | var result = new Stochator({ 299 | kind: "string", 300 | expression: ".{5}!", 301 | unicode: true, 302 | prng: getPrng() 303 | }).next(); 304 | 305 | assert.equal(result, "쁇ڣ馟ᗤ!"); 306 | }); 307 | 308 | it("should generate longer wildcard matches when specified", function() { 309 | var result = new Stochator({ 310 | kind: "string", 311 | expression: "Look at all this binary: ((0|1){256})", 312 | maxWildcard: 256, 313 | prng: getPrng() 314 | }).next(); 315 | 316 | assert.equal(result, [ 317 | 'Look at all this binary: ', 318 | '11010100110000010010111111110101', 319 | '00100100000110111100010101011100', 320 | '10100111010001111100110111010100', 321 | '01001101011111010111110110111101', 322 | '11110110000000111100101001001001', 323 | '00010010101001001000101010110110', 324 | '01011010001111001011111101010011', 325 | '11001000100111101110001001110100' 326 | ].join('')); 327 | }); 328 | 329 | }) 330 | 331 | describe('the integer generator with a mutator', function() { 332 | 333 | it("should return true or false", function() { 334 | var result1 = new Stochator({ 335 | kind: "integer", 336 | min: 0, 337 | max: 1, 338 | seed: 'STOCHATOR' 339 | }, Boolean).next(); 340 | var result2 = Boolean(Stochator.randomInteger(0, 1, getPrng())); 341 | 342 | assert.equal(result1, false); 343 | assert.equal(result2, false); 344 | }); 345 | 346 | }); 347 | 348 | describe('the float generator with mutator', function() { 349 | 350 | it("should return the cosine of a given within given bounds", function() { 351 | var result1 = new Stochator({ 352 | min: 0, 353 | max: Math.PI * 2, 354 | seed: 'STOCHATOR' 355 | }, Math.cos).next(); 356 | var result2 = Math.cos(Stochator.randomFloat(0, Math.PI * 2, getPrng())); 357 | 358 | assert.equal(result1, -0.8253740855106559); 359 | assert.equal(result2, -0.8253740855106559); 360 | }); 361 | 362 | }); 363 | 364 | describe('the integer generator with mutator that uses previous value', function() { 365 | 366 | it("should return 10 integers that are all equal the previous item +/- 1", function() { 367 | var result1 = new Stochator({ 368 | kind: "integer", 369 | min: -1, 370 | max: 1, 371 | seed: 'STOCHATOR' 372 | }, function(a, b) { return a + b; }).next(10); 373 | 374 | var prng = getPrng(); 375 | var sum = 0; 376 | var result2 = _.range(10).map(function() { 377 | sum += Stochator.randomInteger(-1, 1, prng); 378 | return sum; 379 | }); 380 | 381 | assert.deepEqual(result1, [0, 1, 2, 1, 1, 0, 0, -1, -1, 0]); 382 | assert.deepEqual(result2, [0, 1, 2, 1, 1, 0, 0, -1, -1, 0]); 383 | }); 384 | 385 | it("should return 10 numbers that increase by a given fixed amount and a bounded relative change", function() { 386 | var addInterest = function(interestRate, principal) { 387 | return (principal + 1000) * interestRate; 388 | }; 389 | var result1 = new Stochator({ 390 | kind: "float", 391 | min: 1.01, 392 | max: 1.05, 393 | seed: 'STOCHATOR' 394 | }, addInterest).next(10); 395 | 396 | var prng = getPrng(); 397 | var principal = 0; 398 | var result2 = _.range(10).map(function() { 399 | var interestRate = Stochator.randomFloat(1.01, 1.05, prng); 400 | principal = addInterest(interestRate, principal); 401 | return principal; 402 | }); 403 | 404 | assert.deepEqual(result1, [ 405 | 1026.1807151334629, 406 | 2123.8934948333995, 407 | 3248.9834498702794, 408 | 4295.874912610078, 409 | 5475.947903284715, 410 | 6562.853629181616, 411 | 7838.825069340333, 412 | 9010.692918061377, 413 | 10256.214835559122, 414 | 11812.764583986824 415 | ]); 416 | assert.deepEqual(result2, [ 417 | 1026.1807151334629, 418 | 2123.8934948333995, 419 | 3248.9834498702794, 420 | 4295.874912610078, 421 | 5475.947903284715, 422 | 6562.853629181616, 423 | 7838.825069340333, 424 | 9010.692918061377, 425 | 10256.214835559122, 426 | 11812.764583986824 427 | ]); 428 | }); 429 | 430 | }); 431 | 432 | 433 | describe('the integer generator with multiple generators', function() { 434 | 435 | it('should return two integers between the given bounds', function() { 436 | var x = { kind: 'integer', min: 0, max: 480, seed: 'STOCHATOR' }; 437 | var y = { kind: 'integer', min: 0, max: 360, seed: 'STOCHATOR' }; 438 | var result1 = new Stochator(x, y).next(); 439 | 440 | var result2 = [ 441 | Stochator.randomInteger(0, 480, getPrng()), 442 | Stochator.randomInteger(0, 360, getPrng()) 443 | ]; 444 | 445 | assert.deepEqual(result1, [194, 146]); 446 | assert.deepEqual(result2, [194, 146]); 447 | }); 448 | 449 | }); 450 | 451 | 452 | describe('the integer generator with multiple generators and a mutator', function() { 453 | 454 | it('should return an object with x and y values between the given bounds', function() { 455 | var x = { kind: 'integer', min: 0, max: 480, seed: 'STOCHATOR' }; 456 | var y = { kind: 'integer', min: 0, max: 360, seed: 'STOCHATOR' }; 457 | var mutator = function(values) { 458 | return { 459 | x: values[0], 460 | y: values[1] 461 | }; 462 | }; 463 | var result1 = new Stochator(x, y, mutator).next(); 464 | 465 | var result2 = mutator([ 466 | Stochator.randomInteger(0, 480, getPrng()), 467 | Stochator.randomInteger(0, 360, getPrng()) 468 | ]); 469 | 470 | assert.deepEqual(result1, {x: 194, y: 146}); 471 | assert.deepEqual(result2, {x: 194, y: 146}); 472 | }); 473 | 474 | }); 475 | 476 | }); 477 | --------------------------------------------------------------------------------