wilson-interval 5.1.0 → 6.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,73 +1,196 @@
1
1
  # Wilson Interval
2
2
 
3
- [![license](https://img.shields.io/github/license/erikfox/wilson-interval.svg)](https://opensource.org/licenses/MIT)
3
+ [![license](https://img.shields.io/github/license/erikfox/wilson-interval.svg)](LICENSE)
4
4
  [![npm](https://img.shields.io/npm/v/wilson-interval.svg)](https://www.npmjs.com/package/wilson-interval)
5
- [![npm](https://img.shields.io/npm/dt/wilson-interval.svg?colorB=32CD32)](https://www.npmjs.com/package/wilson-interval)
5
+ [![npm downloads](https://img.shields.io/npm/d18m/wilson-interval.svg?colorB=32CD32)](https://www.npmjs.com/package/wilson-interval)
6
6
  [![codecov](https://codecov.io/github/erikfox/wilson-interval/graph/badge.svg?token=R0A2KJQWU6)](https://codecov.io/github/erikfox/wilson-interval)
7
- [![Pull Requests Welcome](https://img.shields.io/badge/pull_requests-welcome-FF69B4.svg)]()
8
- [![](https://img.shields.io/github/issues-raw/erikfox/wilson-interval.svg?colorB=FF69B4)](https://github.com/erikfox/wilson-interval/issues)
7
+ [![Pull Requests Welcome](https://img.shields.io/badge/pull_requests-welcome-FF69B4.svg)](CONTRIBUTING.md)
8
+ [![issues](https://img.shields.io/github/issues-raw/erikfox/wilson-interval.svg?colorB=FF69B4)](https://github.com/erikfox/wilson-interval/issues)
9
9
 
10
- A comprehensive module used to calculate the **high bound**, **low bound**, and **center** of a **[Wilson score interval](http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval)**. Features support for known populations (i.e. **[Singleton's adjustment](https://corplingstats.wordpress.com/2012/04/30/inferential-statistics/)**).
10
+ Calculates the **low bound**, **center** and **high bound** of a **[Wilson score interval](https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval)** for a binomial proportion, with optional **finite population correction** (Singleton's adjustment) and **continuity correction**.
11
11
 
12
- Popularized by **[Reddit's Comment/Best Sort](http://amix.dk/blog/post/19588)** and similar voting algorithms.
12
+ The low bound is a popular way to rank items by their share of positive votes, as described in Evan Miller's **[How Not To Sort By Average Rating](https://www.evanmiller.org/how-not-to-sort-by-average-rating.html)** and used for Reddit's "best" comment sort.
13
13
 
14
- ### Install
14
+ No dependencies, ES module only, TypeScript definitions included. Requires Node.js 22 or later.
15
+
16
+ ## Install
15
17
 
16
18
  ```sh
17
19
  npm install wilson-interval
18
20
  ```
19
21
 
20
- ### Include
22
+ ## Usage
21
23
 
22
24
  ```js
23
25
  import wilson from 'wilson-interval';
26
+
27
+ console.log(wilson(5, 100));
24
28
  ```
25
29
 
26
- ## Usage
30
+ ```text
31
+ {
32
+ high: 0.11175046929755608,
33
+ center: 0.06664707421899263,
34
+ low: 0.02154367914042918
35
+ }
36
+ ```
37
+
38
+ ### `wilson(observed, sample[, options])`
27
39
 
28
- ### wilson(observed, sample[, population ][, confidence ]);
40
+ - `observed`: required. Count of positive outcomes, a whole number from `0` to `sample`.
41
+ - `sample`: required. Sample size, a positive whole number.
42
+ - `options`: optional object.
29
43
 
30
- - `observed` - Required, accepts `Number >= 0`. Count of observed positive outcomes as a whole number.
31
- - `sample` - Required, accepts `Number > 0`. Size of sample as a whole number.
44
+ | Option | Default | Description |
45
+ |---|---|---|
46
+ | `confidence` | `0.95` | Confidence level, a number strictly between 0 and 1. |
47
+ | `population` | none | Size of the finite population the sample was drawn from, a whole number of at least `sample`. Narrows the interval (see [Finite population correction](#finite-population-correction)). |
48
+ | `continuityCorrection` | `false` | Widens the bounds with a continuity correction (see [Continuity correction](#continuity-correction)). |
32
49
 
33
- Optional arguments:
50
+ Returns `{ high, center, low }`, with `0 <= low <= center <= high <= 1`. `center` is the center of the Wilson interval, which is pulled toward 0.5 compared with the observed proportion `observed / sample`.
34
51
 
35
- - `population` - Default `null`, accepts `Number > 0`. Total population from which sample was taken (to use **[Singleton's adjustment](https://corplingstats.wordpress.com/2012/04/30/inferential-statistics/)**<sup>[1]</sup>). Must be a positive whole number.
36
- - `confidence` - Default `0.95`, accepts `1 > Number > 0`. Desired confidence level of interval as a fractional decimal value between 0 and 1.
52
+ Throws an `Error` if an argument is out of range or not a whole number, if an option is misspelled or has the wrong type, or if it's called with the v5 positional arguments (see [Migrating from v5](#migrating-from-v5)).
53
+
54
+ ### Options example
37
55
 
38
- #### Example
39
56
  ```js
40
- return wilson(5, 100);
57
+ import wilson from 'wilson-interval';
58
+
59
+ console.log(wilson(5, 100, { confidence: 0.99 }));
60
+ console.log(wilson(5, 100, { population: 227 }));
61
+ console.log(wilson(5, 100, { continuityCorrection: true }));
41
62
  ```
42
- returns
43
- ```json
63
+
64
+ ```text
65
+ {
66
+ high: 0.13915030303862663,
67
+ center: 0.07799930953114226,
68
+ low: 0.016848316023657876
69
+ }
70
+ {
71
+ high: 0.09258652905391976,
72
+ center: 0.05950886404522964,
73
+ low: 0.02643119903653953
74
+ }
44
75
  {
45
- "center": 0.06664707421899263,
46
- "high": 0.11175046929755608,
47
- "low": 0.02154367914042918
76
+ high: 0.11829946393542573,
77
+ center: 0.06664707421899263,
78
+ low: 0.018552563709170015
48
79
  }
49
80
  ```
50
81
 
82
+ ### TypeScript
83
+
84
+ Types ship with the package. `WilsonOptions` and `WilsonInterval` are exported:
85
+
86
+ ```ts
87
+ import wilson, { type WilsonOptions, type WilsonInterval } from 'wilson-interval';
88
+
89
+ const options: WilsonOptions = { confidence: 0.9 };
90
+ const result: WilsonInterval = wilson(5, 100, options);
91
+ ```
92
+
51
93
  ## Use cases
52
94
 
53
- ### Low bound sorting
95
+ ### Ranking by the low bound
54
96
 
55
- Most often, the **low bound** of the interval will be used as the sorting parameter (e.g. **[Reddit's Comment/Best Sort](http://amix.dk/blog/post/19588)**). This places more importance on confidence than total score.
97
+ Sorting by the low bound puts more weight on confidence than on the raw ratio. An item with one vote, all positive, won't outrank an item with 90 positive votes out of 100 until there is enough data to be confident its ratio really is that high.
56
98
 
57
- Even if a ranked item has 100% positive responses, this ensures it won't be ranked at the top until enough data has been gathered for the algorithm to be confident that that ratio is what it really deserves.
99
+ ```js
100
+ import wilson from 'wilson-interval';
58
101
 
59
- ### Singleton's adjustment
102
+ const items = [
103
+ { name: 'A', positive: 1, total: 1 },
104
+ { name: 'B', positive: 90, total: 100 },
105
+ { name: 'C', positive: 8, total: 10 },
106
+ ];
60
107
 
61
- Uses a known, finite population size to inform the degree of uncertainty of the prediction.
108
+ const ranked = items
109
+ .map((item) => ({ ...item, score: wilson(item.positive, item.total).low }))
110
+ .sort((a, b) => b.score - a.score);
111
+
112
+ console.log(ranked.map((item) => `${item.name} ${item.score.toFixed(3)}`));
113
+ ```
114
+
115
+ ```text
116
+ [ 'B 0.826', 'C 0.490', 'A 0.207' ]
117
+ ```
118
+
119
+ ### Finite population correction
120
+
121
+ Pass `population` when your sample is a significant part of a known, finite population. Observing more of the population leaves less uncertainty, so the interval narrows.
62
122
 
63
123
  > ![Singleton's adjustment](https://corplingstats.files.wordpress.com/2012/04/popsamp1.png?w=538)
64
124
 
65
125
  > Descriptive statistics summarises the sample as if it were the entire population (left), whereas inferential statistics assumes the sample is a tiny subset of the population (right). If the sample is a large part of the population the confidence interval on observations is reduced (middle).<sup>[1]</sup>
66
126
 
67
- **USE WHEN:**
127
+ **Use it when:**
128
+
129
+ 1. Your sample is a significant portion of the population.
130
+ 2. You have an imperfect original sample from which you can only verify a subsample. The original sample can serve as the "population" to produce a verification interval to combine with the first.<sup>[2]</sup>
131
+
132
+ **How it's calculated:** the observed proportion `p = observed / sample` is unchanged. The sample size used for the interval is divided by ν², where ν = √((N − n) / (N − 1)) is the finite population correction.<sup>[1]</sup> If `sample` equals `population`, the whole population was observed and the interval collapses to `p`:
68
133
 
69
- 1. Your sample size represents a significant portion of the population.
70
- 2. You have an imperfect original sample, from which you can only verify a subsample. The original sample can serve as a "population" to produce a verification interval to be combined with the first.<sup>[2]</sup>
134
+ ```js
135
+ import wilson from 'wilson-interval';
136
+
137
+ console.log(wilson(5, 100, { population: 100 }));
138
+ ```
139
+
140
+ ```text
141
+ { high: 0.05, center: 0.05, low: 0.05 }
142
+ ```
143
+
144
+ > **Note:** The worked example in *Coping with imperfect data*<sup>[2]</sup> (5 of 100 from a population of 227, giving 0.0240–0.1011) divides n by ν instead of ν². This module follows the ν² adjustment described in [1], which matches the variance of sampling without replacement, so it returns 0.0264–0.0926 for that example.
145
+
146
+ ### Continuity correction
147
+
148
+ The Wilson interval approximates a discrete distribution with a continuous one. The continuity correction compensates for this by computing the lower bound from `p − 1/(2n)` and the upper bound from `p + 1/(2n)` (clamped to [0, 1]), which makes the interval more conservative.<sup>[3][4]</sup> It is the same interval as R's `prop.test(x, n, correct = TRUE)`.
149
+
150
+ - `center` is not changed by the correction.
151
+ - With `population`, the bounds use the population-adjusted sample size, and the `1/(2n)` shift uses the original sample size.<sup>[3]</sup> If `sample` equals `population`, the interval still collapses to `p`.
152
+
153
+ ## Migrating from v5
154
+
155
+ v6 replaces the positional `population` and `confidence` arguments with an options object:
156
+
157
+ ```js
158
+ // v5
159
+ wilson(5, 100, 227, 0.9);
160
+ wilson(5, 100, null, 0.9);
161
+
162
+ // v6
163
+ wilson(5, 100, { population: 227, confidence: 0.9 });
164
+ wilson(5, 100, { confidence: 0.9 });
165
+ ```
166
+
167
+ Calling v6 with the v5 arguments throws instead of silently returning a different result:
168
+
169
+ ```text
170
+ wilson() takes an options object as its third argument since v6. Replace wilson(observed, sample, population, confidence) with wilson(observed, sample, { population, confidence }).
171
+ ```
172
+
173
+ Other changes in v6:
174
+
175
+ - Node.js 22 or later is required.
176
+ - New `continuityCorrection` option.
177
+ - Misspelled options, such as `{ confidnce: 0.9 }`, now throw.
178
+ - TypeScript definitions are included.
179
+ - Results with `population` changed in v5.1.1 to fix the finite population correction. See the [v5.1.1 release notes](https://github.com/erikfox/wilson-interval/releases/tag/v5.1.1).
180
+
181
+ ## Also exported
182
+
183
+ `normalQuantile(p)` returns the quantile (inverse CDF) of the standard normal distribution, which `wilson()` uses for its critical value.
184
+
185
+ ```js
186
+ import { normalQuantile } from 'wilson-interval';
187
+
188
+ console.log(normalQuantile(0.975));
189
+ ```
190
+
191
+ ```text
192
+ 1.959963986120195
193
+ ```
71
194
 
72
195
  ## Sources
73
196
 
@@ -75,5 +198,9 @@ Uses a known, finite population size to inform the degree of uncertainty of the
75
198
 
76
199
  <sup>[2]</sup> [Wallis, Sean 2014. *Coping with imperfect data*. London: Survey of English Usage, UCL.](https://corplingstats.wordpress.com/2014/04/10/imperfect-data/)
77
200
 
201
+ <sup>[3]</sup> [Wallis, Sean 2019. *Correcting for continuity*. London: Survey of English Usage, UCL.](https://corplingstats.wordpress.com/2019/04/27/correcting-for-continuity/)
202
+
203
+ <sup>[4]</sup> [Newcombe, Robert G. 1998. *Two-sided confidence intervals for the single proportion: comparison of seven methods*. Statistics in Medicine 17(8): 857–872.](https://doi.org/10.1002/(SICI)1097-0258(19980430)17:8%3C857::AID-SIM777%3E3.0.CO;2-E)
204
+
78
205
  ___
79
- *Special thanks to Sean Wallis—Senior Research Fellow, Survey of English Usage—for his aid in transcribing equations, and for his blog posts which inspired many of the features of this module.*
206
+ *Special thanks to [Sean Wallis](https://profiles.ucl.ac.uk/21175-sean-wallis), Principal Research Fellow and Deputy Director of the Survey of English Usage, UCL, for his help transcribing equations, and for the blog posts that inspired many of this module's features.*
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "wilson-interval",
3
- "version": "5.1.0",
3
+ "version": "6.0.0-rc.0",
4
4
  "author": "Erik Fox <eriktfox@gmail.com> (http://erikfox.dev)",
5
- "description": "Used to calculate the high bound, low bound, and center of a Wilson score interval. Features support for continuity correction and Singleton's adjustment.",
5
+ "description": "Wilson score confidence interval for a binomial proportion, with optional finite population and continuity corrections. Zero dependencies, TypeScript types included.",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/erikfox/wilson-interval",
8
8
  "repository": {
@@ -14,6 +14,10 @@
14
14
  },
15
15
  "keywords": [
16
16
  "wilson",
17
+ "wilson-score",
18
+ "binomial",
19
+ "continuity-correction",
20
+ "finite-population-correction",
17
21
  "score",
18
22
  "reddit",
19
23
  "confidence",
@@ -26,15 +30,24 @@
26
30
  "downvotes"
27
31
  ],
28
32
  "engines": {
29
- "node": ">=18.0.0"
33
+ "node": ">=22"
30
34
  },
31
35
  "type": "module",
32
36
  "main": "./src/index.js",
37
+ "types": "./src/index.d.ts",
38
+ "files": [
39
+ "src/index.js",
40
+ "src/index.d.ts"
41
+ ],
33
42
  "exports": {
34
- ".": "./src/index.js"
43
+ ".": {
44
+ "types": "./src/index.d.ts",
45
+ "default": "./src/index.js"
46
+ }
35
47
  },
36
48
  "scripts": {
37
49
  "test": "node --test src/index.test.js",
50
+ "test:types": "npx -y -p typescript@7.0.2 tsc -p test/tsconfig.json",
38
51
  "test:cc": "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info src/index.test.js"
39
52
  }
40
53
  }
package/src/index.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ /** Options for {@link wilson}. Omitted or `undefined` options use their defaults. */
2
+ export interface WilsonOptions {
3
+ /**
4
+ * Size of the finite population the sample was drawn from (a positive whole
5
+ * number, at least `sample`). Narrows the interval with the finite population
6
+ * correction; if `sample` equals `population`, the interval collapses to p.
7
+ * Default: no population (an infinite population).
8
+ */
9
+ population?: number | undefined;
10
+
11
+ /**
12
+ * Confidence level of the interval, strictly between 0 and 1.
13
+ * @default 0.95
14
+ */
15
+ confidence?: number | undefined;
16
+
17
+ /**
18
+ * Apply a continuity correction (Newcombe 1998 method 4; Wallis 2019), which
19
+ * widens the bounds. `center` is unchanged.
20
+ * @default false
21
+ */
22
+ continuityCorrection?: boolean | undefined;
23
+ }
24
+
25
+ /** A Wilson score interval. Always `0 <= low <= center <= high <= 1`. */
26
+ export interface WilsonInterval {
27
+ /** Upper bound of the interval. */
28
+ high: number;
29
+ /** Center of the Wilson score interval (not the observed proportion). */
30
+ center: number;
31
+ /** Lower bound of the interval. Often used as a ranking score. */
32
+ low: number;
33
+ }
34
+
35
+ /**
36
+ * Calculates the Wilson score interval for a binomial proportion.
37
+ *
38
+ * @param observed Count of positive outcomes, a whole number from 0 to `sample`.
39
+ * @param sample Sample size, a positive whole number.
40
+ * @param options Population size, confidence level and continuity correction.
41
+ * @returns The interval's `high`, `center` and `low`.
42
+ * @throws {Error} If an argument is out of range, an option is unknown, or the
43
+ * v5 positional form `wilson(observed, sample, population, confidence)` is used.
44
+ *
45
+ * @example
46
+ * wilson(5, 100);
47
+ * // { high: 0.1118, center: 0.0666, low: 0.0215 } (rounded)
48
+ *
49
+ * wilson(5, 100, { population: 227, confidence: 0.9 });
50
+ */
51
+ export default function wilson(
52
+ observed: number,
53
+ sample: number,
54
+ options?: WilsonOptions
55
+ ): WilsonInterval;
56
+
57
+ /**
58
+ * Quantile (inverse CDF) of the standard normal distribution.
59
+ *
60
+ * @param p A probability from 0 to 1. Returns `-Infinity` at 0 and `Infinity` at 1.
61
+ * @throws {Error} If `p` is outside [0, 1] or NaN.
62
+ */
63
+ export function normalQuantile(p: number): number;
package/src/index.js CHANGED
@@ -1,36 +1,92 @@
1
- export default function wilson(observed, sample, population = null, confidence = 0.95) {
2
- observed = Number(observed);
3
- sample = Number(sample);
4
- confidence = Number(confidence);
1
+ const OPTIONS = ['population', 'confidence', 'continuityCorrection'];
5
2
 
6
- if (observed < 0) {
3
+ const MIGRATION_ERROR =
4
+ 'wilson() takes an options object as its third argument since v6. ' +
5
+ 'Replace wilson(observed, sample, population, confidence) with ' +
6
+ 'wilson(observed, sample, { population, confidence }).';
7
+
8
+ export default function wilson(observed, sample, options = {}) {
9
+ // v5 took population and confidence as positional arguments; catch those
10
+ // calls explicitly rather than misreading them
11
+ if (arguments.length > 3 || typeof options === 'number' || options === null) {
12
+ throw new Error(MIGRATION_ERROR);
13
+ }
14
+
15
+ if (typeof options !== 'object' || Array.isArray(options)) {
16
+ throw new Error('Options must be an object');
17
+ }
18
+
19
+ for (const key of Object.keys(options)) {
20
+ if (!OPTIONS.includes(key)) {
21
+ throw new Error(`Unknown option "${key}" (expected one of: ${OPTIONS.join(', ')})`);
22
+ }
23
+ }
24
+
25
+ const { population, confidence = 0.95, continuityCorrection = false } = options;
26
+
27
+ if (!Number.isSafeInteger(observed) || observed < 0) {
7
28
  throw new Error('Observed must be a non-negative whole number');
8
29
  }
9
30
 
10
- if (sample <= 0) {
31
+ if (!Number.isSafeInteger(sample) || sample <= 0) {
11
32
  throw new Error('Sample must be a positive whole number');
12
33
  }
13
34
 
14
- if (confidence <= 0 || confidence >= 1) {
35
+ if (observed > sample) {
36
+ throw new Error('Observed must not exceed sample');
37
+ }
38
+
39
+ if (typeof confidence !== 'number' || Number.isNaN(confidence) || confidence <= 0 || confidence >= 1) {
15
40
  throw new Error('Confidence must be a decimal between 0 and 1');
16
41
  }
17
42
 
18
- if (Number.isSafeInteger(population)) {
19
- if (population <= 0) {
43
+ if (typeof continuityCorrection !== 'boolean') {
44
+ throw new Error('Continuity correction must be true or false');
45
+ }
46
+
47
+ const p = observed / sample;
48
+ let n = sample;
49
+
50
+ if (population !== undefined) {
51
+ if (!Number.isSafeInteger(population) || population <= 0) {
20
52
  throw new Error('Population must be a positive whole number');
21
53
  }
22
- sample = sample / Math.sqrt(1 - sample / population);
54
+ if (sample > population) {
55
+ throw new Error('Sample must not exceed population');
56
+ }
57
+ // The whole population was observed, so there is no uncertainty
58
+ if (sample === population) {
59
+ return { high: p, center: p, low: p };
60
+ }
61
+ // Finite population correction: the standard deviation scales by
62
+ // ν = √((N − n) / (N − 1)), the exact hypergeometric factor, which is
63
+ // equivalent to dividing n by ν². p is unchanged.
64
+ // See Wallis (2012), "Inferential statistics — and other animals".
65
+ n = sample * (population - 1) / (population - sample);
23
66
  }
24
67
 
25
- const zScore = normalQuantile(1 - (1 - confidence) / 2);
68
+ // Computed from the lower tail so confidence near 1 keeps its precision
69
+ // (1 − (1 − confidence) / 2 can round to exactly 1 and give z = Infinity)
70
+ const z = -normalQuantile((1 - confidence) / 2);
26
71
 
27
- const p = observed / sample;
28
- const n = sample;
29
- const z = zScore;
72
+ const { center, low: scoreLow, high: scoreHigh } = scoreInterval(p, n, z);
73
+ let low = scoreLow;
74
+ let high = scoreHigh;
75
+
76
+ if (continuityCorrection) {
77
+ // Wilson bounds of p ∓ 1/(2n), clamped to [0, 1]. The shift uses the
78
+ // original sample size even when n is adjusted for a population.
79
+ // center stays the uncorrected Wilson center.
80
+ // See Wallis (2019), "Correcting for continuity", Eq. 9.
81
+ const shift = 1 / (2 * sample);
82
+ low = Math.min(low, scoreInterval(Math.max(p - shift, 0), n, z).low);
83
+ high = Math.max(high, scoreInterval(Math.min(p + shift, 1), n, z).high);
84
+ }
30
85
 
31
- const high = ((p + z * z / (2 * n) + z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))) / (1 + z * z / n));
32
- const low = ((p + z * z / (2 * n) - z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))) / (1 + z * z / n));
33
- const center = ((p + z * z / (2 * n)) / (1 + z * z / n));
86
+ // The bounds are exactly 0 at p = 0 and exactly 1 at p = 1; elsewhere, clamp
87
+ // away floating-point drift so that 0 ≤ low ≤ p ≤ high ≤ 1 always holds
88
+ low = observed === 0 ? 0 : Math.max(0, Math.min(low, p));
89
+ high = observed === sample ? 1 : Math.min(1, Math.max(high, p));
34
90
 
35
91
  return {
36
92
  high,
@@ -39,10 +95,18 @@ export default function wilson(observed, sample, population = null, confidence =
39
95
  };
40
96
  }
41
97
 
98
+ // Wilson score interval for proportion p with sample size n and critical value z
99
+ function scoreInterval(p, n, z) {
100
+ const denominator = 1 + z * z / n;
101
+ const center = (p + z * z / (2 * n)) / denominator;
102
+ const margin = z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denominator;
103
+ return { center, low: center - margin, high: center + margin };
104
+ }
105
+
42
106
  // Returns the quantile (inverse CDF) for the standard normal distribution
43
107
  export function normalQuantile(p) {
44
- if (p < 0 || p > 1) {
45
- throw new Error('The probability p must be between 0 and 1');
108
+ if (Number.isNaN(p) || p < 0 || p > 1) {
109
+ throw new Error('p must be a decimal between 0 and 1');
46
110
  }
47
111
  if (p === 0) return -Infinity;
48
112
  if (p === 1) return Infinity;
package/.editorconfig DELETED
@@ -1,13 +0,0 @@
1
- # editorconfig.org
2
- root = true
3
-
4
- [*]
5
- charset = utf-8
6
- end_of_line = lf
7
- indent_style = space
8
- indent_size = 2
9
- insert_final_newline = true
10
- trim_trailing_whitespace = true
11
-
12
- [*.md]
13
- trim_trailing_whitespace = false
@@ -1,11 +0,0 @@
1
- # To get started with Dependabot version updates, you'll need to specify which
2
- # package ecosystems to update and where the package manifests are located.
3
- # Please see the documentation for all configuration options:
4
- # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
5
-
6
- version: 2
7
- updates:
8
- - package-ecosystem: "npm" # See documentation for possible values
9
- directory: "/" # Location of package manifests
10
- schedule:
11
- interval: "weekly"
@@ -1,23 +0,0 @@
1
- # Adapted from https://github.com/codecov/example-javascript
2
- name: Codecov Test Coverage Report
3
- on: [pull_request]
4
- jobs:
5
- build:
6
-
7
- runs-on: ubuntu-latest
8
-
9
- steps:
10
- - uses: actions/checkout@v4
11
- - name: Use Node.js ${{ matrix.node-version }}
12
- uses: actions/setup-node@v4
13
- with:
14
- node-version: 21 # Node native test coverage reporting introduced in v20.11.0
15
- cache: 'npm'
16
- - run: npm ci
17
- - run: npm run build --if-present
18
- - run: npm run test:cc
19
- - name: Upload coverage reports to Codecov
20
- uses: codecov/codecov-action@v5
21
- with:
22
- token: ${{ secrets.CODECOV_TOKEN }}
23
- slug: erikfox/wilson-interval
@@ -1,31 +0,0 @@
1
- # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
2
- # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
3
-
4
- name: Node.js CI
5
-
6
- on:
7
- push:
8
- branches: [ "master" ]
9
- pull_request:
10
- branches: [ "master" ]
11
-
12
- jobs:
13
- build:
14
-
15
- runs-on: ubuntu-latest
16
-
17
- strategy:
18
- matrix:
19
- node-version: [18.x, 20.x, 22.x]
20
- # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
21
-
22
- steps:
23
- - uses: actions/checkout@v4
24
- - name: Use Node.js ${{ matrix.node-version }}
25
- uses: actions/setup-node@v4
26
- with:
27
- node-version: ${{ matrix.node-version }}
28
- cache: 'npm'
29
- - run: npm ci
30
- - run: npm run build --if-present
31
- - run: npm test
@@ -1,33 +0,0 @@
1
- # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
- # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
-
4
- name: Node.js Package
5
-
6
- on:
7
- release:
8
- types: [created]
9
-
10
- jobs:
11
- build:
12
- runs-on: ubuntu-latest
13
- steps:
14
- - uses: actions/checkout@v4
15
- - uses: actions/setup-node@v4
16
- with:
17
- node-version: 20
18
- - run: npm ci
19
- - run: npm test
20
-
21
- publish-npm:
22
- needs: build
23
- runs-on: ubuntu-latest
24
- steps:
25
- - uses: actions/checkout@v4
26
- - uses: actions/setup-node@v4
27
- with:
28
- node-version: 20
29
- registry-url: https://registry.npmjs.org/
30
- - run: npm ci
31
- - run: npm publish
32
- env:
33
- NODE_AUTH_TOKEN: ${{secrets.npm_token}}
package/codecov.yml DELETED
@@ -1,25 +0,0 @@
1
- coverage:
2
- status:
3
- project:
4
- default: # default is the status check's name, not default settings
5
- target: 100%
6
- threshold: 1%
7
- base: auto
8
- flags:
9
- - unit
10
- paths:
11
- - "src"
12
- # advanced settings
13
- branches:
14
- - master
15
- if_ci_failed: error #success, failure, error, ignore
16
- informational: false
17
- only_pulls: false
18
-
19
- comment:
20
- layout: " diff, flags, files"
21
- behavior: default
22
- require_changes: false
23
- require_base: false
24
- require_head: true
25
- hide_project_coverage: false
package/src/index.test.js DELETED
@@ -1,111 +0,0 @@
1
- import wilson, { normalQuantile } from './index.js';
2
- import test from 'node:test';
3
- import assert from 'node:assert';
4
- import { describe } from 'node:test';
5
-
6
- describe('wilson()', () => {
7
- describe('handles base args', () => {
8
- test('wilson(5, 100)', () => {
9
- const result = wilson(5, 100);
10
-
11
- assert.deepEqual(result, {
12
- center: 0.06664707421899263,
13
- high: 0.11175046929755608,
14
- low: 0.02154367914042918
15
- });
16
- });
17
-
18
- test('wilson(-1, 100)', () => {
19
- assert.throws(() => wilson(-1, 100), {
20
- message: 'Observed must be a non-negative whole number'
21
- });
22
- });
23
-
24
- test('wilson(5, 0)', () => {
25
- assert.throws(() => wilson(5, 0), {
26
- message: 'Sample must be a positive whole number'
27
- });
28
- });
29
- });
30
-
31
- describe('handles population arg', () => {
32
- test('wilson(5, 100, 227)', () => {
33
- const result = wilson(5, 100, 227);
34
-
35
- assert.deepEqual(result, {
36
- center: 0.050319696641804315,
37
- high: 0.08456089359579015,
38
- low: 0.016078499687818482
39
- });
40
- });
41
-
42
- test('wilson(5, 100, 0)', () => {
43
- assert.throws(() => wilson(5, 100, 0), {
44
- message: 'Population must be a positive whole number'
45
- });
46
- });
47
- });
48
-
49
- describe('handles confidence arg', () => {
50
- test('wilson(5, 100, 227, 0.9)', () => {
51
- const result = wilson(5, 100, 227, 0.9);
52
-
53
- assert.deepEqual(result, {
54
- center: 0.04657481789797846,
55
- high: 0.0748286439672683,
56
- low: 0.018320991828688626
57
- });
58
- });
59
-
60
- test('wilson(5, 100, 227, 1)', () => {
61
- assert.throws(() => wilson(5, 100, 227, 1), {
62
- message: 'Confidence must be a decimal between 0 and 1'
63
- });
64
- });
65
- });
66
- });
67
-
68
- describe('normalQuantile()', () => {
69
- describe('handles base args', () => {
70
- test('normalQuantile(0.95)', () => {
71
- const result = normalQuantile(0.95);
72
- assert.strictEqual(result, 1.644853625133699);
73
- });
74
-
75
- test('normalQuantile(0.01)', () => {
76
- const result = normalQuantile(0.01);
77
- assert.strictEqual(result, -2.326347874388028);
78
- });
79
-
80
- test('normalQuantile(0.99)', () => {
81
- const result = normalQuantile(0.99);
82
- assert.strictEqual(result, 2.326347874388028);
83
- });
84
- });
85
-
86
- describe('handles edge cases', () => {
87
- test('normalQuantile(0)', () => {
88
- const result = normalQuantile(0);
89
- assert.strictEqual(result, -Infinity);
90
- });
91
-
92
- test('normalQuantile(1)', () => {
93
- const result = normalQuantile(1);
94
- assert.strictEqual(result, Infinity);
95
- });
96
- });
97
-
98
- describe('throws on invalid args', () => {
99
- test('normalQuantile(-1)', () => {
100
- assert.throws(() => normalQuantile(-1), {
101
- message: 'The probability p must be between 0 and 1'
102
- });
103
- });
104
-
105
- test('normalQuantile(2)', () => {
106
- assert.throws(() => normalQuantile(2), {
107
- message: 'The probability p must be between 0 and 1'
108
- });
109
- });
110
- });
111
- });