| 1 |
;; A general-purpose function for generating random values. |
| 2 |
|
| 3 |
(local random-char |
| 4 |
(fn [] |
| 5 |
(if (> (math.random) 0.9) ; digits |
| 6 |
(string.char (+ 47 (math.random 10))) |
| 7 |
(> (math.random) 0.5) ; lower case |
| 8 |
(string.char (+ 96 (math.random 26))) |
| 9 |
(> (math.random) 0.5) ; upper case |
| 10 |
(string.char (+ 64 (math.random 26))) |
| 11 |
(> (math.random) 0.5) ; space and punctuation |
| 12 |
(string.char (+ 31 (math.random 16))) |
| 13 |
(> (math.random) 0.5) ; newlines and tabs |
| 14 |
(string.char (+ 9 (math.random 4))) |
| 15 |
:else ; bonus punctuation |
| 16 |
(string.char (+ 58 (math.random 5)))))) |
| 17 |
|
| 18 |
(local generators {:number (fn [] ; weighted towards mid-range integers |
| 19 |
(if (> (math.random) 0.9) |
| 20 |
(let [x (math.random 2147483647)] |
| 21 |
(math.floor (- x (/ x 2)))) |
| 22 |
(> (math.random) 0.2) |
| 23 |
(math.floor (math.random 2048)) |
| 24 |
:else (math.random))) |
| 25 |
:string (fn [] |
| 26 |
(var s "") |
| 27 |
(for [_ 1 (math.random 16)] |
| 28 |
(set s (.. s (random-char)))) |
| 29 |
s) |
| 30 |
:table (fn [generate depth] |
| 31 |
(let [t {}] |
| 32 |
(var k nil) |
| 33 |
(for [_ 1 (math.random 16)] |
| 34 |
(set k (generate depth)) |
| 35 |
;; no nans plz |
| 36 |
(while (not= k k) (set k (generate depth))) |
| 37 |
(when (not= nil k) |
| 38 |
(tset t k (generate depth)))) |
| 39 |
t)) |
| 40 |
:sequence (fn [generate depth] |
| 41 |
(let [t {}] |
| 42 |
(for [_ 1 (math.random 32)] |
| 43 |
(tset t (+ (length t) 1) (generate depth))) |
| 44 |
t)) |
| 45 |
:boolean (fn [] (> (math.random) 0.5)) |
| 46 |
:list (fn [] [])}) |
| 47 |
|
| 48 |
(local order [:number :string :table :sequence :boolean]) |
| 49 |
|
| 50 |
(fn generate [depth ?choice] |
| 51 |
"Generate a random piece of data." |
| 52 |
(if (< (+ 0.5 (/ (math.log depth 10) 1.2)) (math.random)) |
| 53 |
(match (. generators (or (. order (or ?choice 1)) :boolean)) |
| 54 |
generator (generator generate (+ depth 1))) |
| 55 |
(or (= nil ?choice) (<= ?choice (length order))) |
| 56 |
(generate depth (+ (or ?choice 1) 1)))) |
| 57 |
|
| 58 |
{: generate : generators : order} |