/
Sampler.ts
121 lines (116 loc) · 4.64 KB
/
Sampler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import { Stream, stream } from '../../stream/Stream';
import { Arbitrary } from '../arbitrary/definition/Arbitrary';
import { Shrinkable } from '../arbitrary/definition/Shrinkable';
import { IRawProperty } from '../property/IRawProperty';
import { Property } from '../property/Property.generic';
import { UnbiasedProperty } from '../property/UnbiasedProperty';
import { readConfigureGlobal } from './configuration/GlobalParameters';
import { Parameters } from './configuration/Parameters';
import { QualifiedParameters } from './configuration/QualifiedParameters';
import { toss } from './Tosser';
import { pathWalk } from './utils/PathWalker';
/** @internal */
function toProperty<Ts>(
generator: IRawProperty<Ts> | Arbitrary<Ts>,
qParams: QualifiedParameters<Ts>
): IRawProperty<Ts> {
const prop = !Object.prototype.hasOwnProperty.call(generator, 'isAsync')
? new Property(generator as Arbitrary<Ts>, () => true)
: (generator as IRawProperty<Ts>);
return qParams.unbiased === true ? new UnbiasedProperty(prop) : prop;
}
/** @internal */
function streamSample<Ts>(
generator: IRawProperty<Ts> | Arbitrary<Ts>,
params?: Parameters<Ts> | number
): IterableIterator<Ts> {
const extendedParams =
typeof params === 'number'
? { ...(readConfigureGlobal() as Parameters<Ts>), numRuns: params }
: { ...(readConfigureGlobal() as Parameters<Ts>), ...params };
const qParams: QualifiedParameters<Ts> = QualifiedParameters.read<Ts>(extendedParams);
const tossedValues: Stream<() => Shrinkable<Ts>> = stream(
toss(toProperty(generator, qParams), qParams.seed, qParams.randomType, qParams.examples)
);
if (qParams.path.length === 0) {
return tossedValues.take(qParams.numRuns).map((s) => s().value_);
}
return stream(
pathWalk(
qParams.path,
tossedValues.map((s) => s())
)
)
.take(qParams.numRuns)
.map((s) => s.value_);
}
/**
* Generate an array containing all the values that would have been generated during {@link assert} or {@link check}
*
* @example
* ```typescript
* fc.sample(fc.nat(), 10); // extract 10 values from fc.nat() Arbitrary
* fc.sample(fc.nat(), {seed: 42}); // extract values from fc.nat() as if we were running fc.assert with seed=42
* ```
*
* @param generator - {@link IProperty} or {@link Arbitrary} to extract the values from
* @param params - Integer representing the number of values to generate or `Parameters` as in {@link assert}
*
* @remarks Since 0.0.6
* @public
*/
function sample<Ts>(generator: IRawProperty<Ts> | Arbitrary<Ts>, params?: Parameters<Ts> | number): Ts[] {
return [...streamSample(generator, params)];
}
/**
* Gather useful statistics concerning generated values
*
* Print the result in `console.log` or `params.logger` (if defined)
*
* @example
* ```typescript
* fc.statistics(
* fc.nat(999),
* v => v < 100 ? 'Less than 100' : 'More or equal to 100',
* {numRuns: 1000, logger: console.log});
* // Classify 1000 values generated by fc.nat(999) into two categories:
* // - Less than 100
* // - More or equal to 100
* // The output will be sent line by line to the logger
* ```
*
* @param generator - {@link IProperty} or {@link Arbitrary} to extract the values from
* @param classify - Classifier function that can classify the generated value in zero, one or more categories (with free labels)
* @param params - Integer representing the number of values to generate or `Parameters` as in {@link assert}
*
* @remarks Since 0.0.6
* @public
*/
function statistics<Ts>(
generator: IRawProperty<Ts> | Arbitrary<Ts>,
classify: (v: Ts) => string | string[],
params?: Parameters<Ts> | number
): void {
const extendedParams =
typeof params === 'number'
? { ...(readConfigureGlobal() as Parameters<Ts>), numRuns: params }
: { ...(readConfigureGlobal() as Parameters<Ts>), ...params };
const qParams: QualifiedParameters<Ts> = QualifiedParameters.read<Ts>(extendedParams);
const recorded: { [key: string]: number } = {};
for (const g of streamSample(generator, params)) {
const out = classify(g);
const categories: string[] = Array.isArray(out) ? out : [out];
for (const c of categories) {
recorded[c] = (recorded[c] || 0) + 1;
}
}
const data = Object.entries(recorded)
.sort((a, b) => b[1] - a[1])
.map((i) => [i[0], `${((i[1] * 100.0) / qParams.numRuns).toFixed(2)}%`]);
const longestName = data.map((i) => i[0].length).reduce((p, c) => Math.max(p, c), 0);
const longestPercent = data.map((i) => i[1].length).reduce((p, c) => Math.max(p, c), 0);
for (const item of data) {
qParams.logger(`${item[0].padEnd(longestName, '.')}..${item[1].padStart(longestPercent, '.')}`);
}
}
export { sample, statistics };