wilson-interval 5.1.1 → 6.0.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,85 +1,206 @@
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:**
68
128
 
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>
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>
71
131
 
72
- **HOW IT'S CALCULATED:**
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`:
73
133
 
74
- 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 interval collapses to `p`.
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
+ ```
75
143
 
76
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.
77
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
+ ```
194
+
78
195
  ## Sources
79
196
 
80
197
  <sup>[1]</sup> [Wallis, Sean 2012. *Inferential Statistics — and other animals*. London: Survey of English Usage, UCL.](https://corplingstats.wordpress.com/2012/04/30/inferential-statistics/)
81
198
 
82
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/)
83
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
+
84
205
  ___
85
- *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.1",
3
+ "version": "6.0.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 Singleton's adjustment (finite population correction).",
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,4 +1,29 @@
1
- export default function wilson(observed, sample, population = null, confidence = 0.95) {
1
+ const OPTIONS = ['population', 'confidence', 'continuityCorrection'];
2
+
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
+
2
27
  if (!Number.isSafeInteger(observed) || observed < 0) {
3
28
  throw new Error('Observed must be a non-negative whole number');
4
29
  }
@@ -15,10 +40,14 @@ export default function wilson(observed, sample, population = null, confidence =
15
40
  throw new Error('Confidence must be a decimal between 0 and 1');
16
41
  }
17
42
 
43
+ if (typeof continuityCorrection !== 'boolean') {
44
+ throw new Error('Continuity correction must be true or false');
45
+ }
46
+
18
47
  const p = observed / sample;
19
48
  let n = sample;
20
49
 
21
- if (population !== null) {
50
+ if (population !== undefined) {
22
51
  if (!Number.isSafeInteger(population) || population <= 0) {
23
52
  throw new Error('Population must be a positive whole number');
24
53
  }
@@ -40,14 +69,24 @@ export default function wilson(observed, sample, population = null, confidence =
40
69
  // (1 − (1 − confidence) / 2 can round to exactly 1 and give z = Infinity)
41
70
  const z = -normalQuantile((1 - confidence) / 2);
42
71
 
43
- const denominator = 1 + z * z / n;
44
- const center = (p + z * z / (2 * n)) / denominator;
45
- const margin = z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denominator;
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
+ }
46
85
 
47
86
  // The bounds are exactly 0 at p = 0 and exactly 1 at p = 1; elsewhere, clamp
48
87
  // away floating-point drift so that 0 ≤ low ≤ p ≤ high ≤ 1 always holds
49
- const low = observed === 0 ? 0 : Math.max(0, Math.min(center - margin, p));
50
- const high = observed === sample ? 1 : Math.min(1, Math.max(center + margin, p));
88
+ low = observed === 0 ? 0 : Math.max(0, Math.min(low, p));
89
+ high = observed === sample ? 1 : Math.min(1, Math.max(high, p));
51
90
 
52
91
  return {
53
92
  high,
@@ -56,6 +95,14 @@ export default function wilson(observed, sample, population = null, confidence =
56
95
  };
57
96
  }
58
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
+
59
106
  // Returns the quantile (inverse CDF) for the standard normal distribution
60
107
  export function normalQuantile(p) {
61
108
  if (Number.isNaN(p) || p < 0 || p > 1) {
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,41 +0,0 @@
1
- # Runs the tests, then publishes the package to npm when a GitHub release is created.
2
- # Authenticates with npm trusted publishing (OIDC), so no npm token secret is needed,
3
- # and npm adds a provenance attestation automatically.
4
- # See https://docs.npmjs.com/trusted-publishers
5
-
6
- name: Node.js Package
7
-
8
- on:
9
- release:
10
- types: [created]
11
-
12
- permissions:
13
- contents: read
14
-
15
- jobs:
16
- build:
17
- runs-on: ubuntu-latest
18
- steps:
19
- - uses: actions/checkout@v4
20
- - uses: actions/setup-node@v4
21
- with:
22
- node-version: 24
23
- - run: npm ci
24
- - run: npm test
25
-
26
- publish-npm:
27
- needs: build
28
- runs-on: ubuntu-latest
29
- permissions:
30
- contents: read
31
- id-token: write # lets npm exchange a GitHub OIDC token for publish rights
32
- steps:
33
- - uses: actions/checkout@v4
34
- - uses: actions/setup-node@v4
35
- with:
36
- node-version: 24
37
- registry-url: https://registry.npmjs.org/
38
- # Trusted publishing needs npm 11.5.1 or later
39
- - run: npm install -g npm@latest
40
- - run: npm ci
41
- - run: npm publish
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,203 +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
- // normalQuantile() has ~1e-9 relative error, so compare with a tolerance
7
- function assertInterval(actual, expected, tolerance = 1e-9) {
8
- for (const key of ['low', 'center', 'high']) {
9
- assert.ok(
10
- Math.abs(actual[key] - expected[key]) < tolerance,
11
- `${key}: expected ${expected[key]}, got ${actual[key]}`
12
- );
13
- }
14
- assert.ok(actual.low <= actual.center && actual.center <= actual.high, 'low <= center <= high');
15
- }
16
-
17
- function assertBounds({ low, center, high }, p) {
18
- assert.ok(0 <= low, `low ${low} < 0`);
19
- assert.ok(low <= p && p <= high, `p ${p} not within [${low}, ${high}]`);
20
- assert.ok(low <= center && center <= high, `center ${center} not within [${low}, ${high}]`);
21
- assert.ok(high <= 1, `high ${high} > 1`);
22
- }
23
-
24
- describe('wilson() bounds', () => {
25
- test('observed = 0 gives low exactly 0', () => {
26
- assert.strictEqual(wilson(0, 1e6, 1000001).low, 0);
27
- assert.strictEqual(wilson(0, 1, 10, 0.99).low, 0);
28
- });
29
-
30
- test('observed = sample gives high exactly 1', () => {
31
- assert.strictEqual(wilson(100, 100, 101).high, 1);
32
- assert.strictEqual(wilson(1e6, 1e6).high, 1);
33
- assert.strictEqual(wilson(1, 1, null, 0.99).high, 1);
34
- });
35
-
36
- test('0 <= low <= p <= high <= 1 across a grid of inputs', () => {
37
- const confidences = [0.5, 0.8, 0.9, 0.95, 0.99, 0.999];
38
- for (let sample = 1; sample <= 120; sample++) {
39
- for (const population of [null, sample, sample + 1, sample * 2, sample * 50]) {
40
- for (const confidence of confidences) {
41
- for (let observed = 0; observed <= sample; observed++) {
42
- assertBounds(wilson(observed, sample, population, confidence), observed / sample);
43
- }
44
- }
45
- }
46
- }
47
- });
48
-
49
- test('very large sample stays within bounds', () => {
50
- const sample = 2 ** 53 - 1;
51
- assertBounds(wilson(sample - 1, sample), (sample - 1) / sample);
52
- });
53
- });
54
-
55
- describe('wilson()', () => {
56
- describe('handles required args', () => {
57
- test('good `observed` and `sample` input', () => {
58
- const result = wilson(5, 100);
59
-
60
- assert.deepEqual(result, {
61
- center: 0.06664707421899263,
62
- high: 0.11175046929755608,
63
- low: 0.02154367914042918
64
- });
65
- });
66
-
67
- test('bad `observed` = -1 input', () => {
68
- assert.throws(() => wilson(-1, 100), {
69
- message: 'Observed must be a non-negative whole number'
70
- });
71
- });
72
-
73
- test('bad `sample` = 0 input', () => {
74
- assert.throws(() => wilson(5, 0), {
75
- message: 'Sample must be a positive whole number'
76
- });
77
- });
78
-
79
- test('bad `observed` > `sample` input', () => {
80
- assert.throws(() => wilson(11, 10), {
81
- message: 'Observed must not exceed sample'
82
- });
83
- });
84
- });
85
-
86
- describe('handles `population` arg', () => {
87
- // Reference values from an independent Python implementation:
88
- // p unchanged, effective n' = n / ν², ν² = (N − n) / (N − 1).
89
- test('good `population` input', () => {
90
- assertInterval(wilson(5, 100, 227), {
91
- center: 0.05950886403022134,
92
- high: 0.0925865290106502,
93
- low: 0.026431199049792478
94
- });
95
- });
96
-
97
- test('`population` = `sample` + 1 with one draw is unadjusted', () => {
98
- // Exact finite-population factor for n = 1 is 1, so n' = n
99
- assertInterval(wilson(1, 1, 2), wilson(1, 1));
100
- });
101
-
102
- test('`sample` = `population` collapses the interval to p', () => {
103
- assert.deepEqual(wilson(5, 100, 100), { high: 0.05, center: 0.05, low: 0.05 });
104
- });
105
-
106
- test('very large `population` matches no population', () => {
107
- assertInterval(wilson(5, 100, 1e12), wilson(5, 100));
108
- });
109
-
110
- test('bad `population` = 0 input', () => {
111
- assert.throws(() => wilson(5, 100, 0), {
112
- message: 'Population must be a positive whole number'
113
- });
114
- });
115
-
116
- test('bad `sample` > `population` input', () => {
117
- assert.throws(() => wilson(5, 100, 50), {
118
- message: 'Sample must not exceed population'
119
- });
120
- });
121
- });
122
-
123
- describe('handles `confidence` arg', () => {
124
- test('good `confidence` input', () => {
125
- assertInterval(wilson(5, 100, 227, 0.9), {
126
- center: 0.05673921186382623,
127
- high: 0.084248814348019,
128
- low: 0.02922960937963347
129
- });
130
- });
131
-
132
- test('`confidence` very close to 1 stays finite', () => {
133
- const result = wilson(5, 100, null, 1 - 1e-16);
134
- for (const key of ['low', 'center', 'high']) {
135
- assert.ok(Number.isFinite(result[key]), `${key} is ${result[key]}`);
136
- }
137
- assertBounds(result, 0.05);
138
- });
139
-
140
- test('bad `confidence` = 1 input', () => {
141
- assert.throws(() => wilson(5, 100, 227, 1), {
142
- message: 'Confidence must be a decimal between 0 and 1'
143
- });
144
- });
145
-
146
- test('bad `confidence` = 0 input', () => {
147
- assert.throws(() => wilson(5, 100, 227, 0), {
148
- message: 'Confidence must be a decimal between 0 and 1'
149
- });
150
- });
151
-
152
- test('bad `confidence` = "0.9" (string) input', () => {
153
- assert.throws(() => wilson(5, 100, null, '0.9'), {
154
- message: 'Confidence must be a decimal between 0 and 1'
155
- });
156
- });
157
- });
158
- });
159
-
160
- describe('normalQuantile()', () => {
161
- describe('handles basic usage', () => {
162
- test('good `p` input', () => {
163
- const result = normalQuantile(0.95);
164
- assert.strictEqual(result, 1.644853625133699);
165
- });
166
-
167
- test('low `p` input', () => {
168
- const result = normalQuantile(0.01);
169
- assert.strictEqual(result, -2.326347874388028);
170
- });
171
-
172
- test('high `p` input', () => {
173
- const result = normalQuantile(0.99);
174
- assert.strictEqual(result, 2.326347874388028);
175
- });
176
- });
177
-
178
- describe('handles edge cases', () => {
179
- test('`p` = 0 input', () => {
180
- const result = normalQuantile(0);
181
- assert.strictEqual(result, -Infinity);
182
- });
183
-
184
- test('`p` = 1 input', () => {
185
- const result = normalQuantile(1);
186
- assert.strictEqual(result, Infinity);
187
- });
188
- });
189
-
190
- describe('throws on invalid args', () => {
191
- test('bad `p` < 0 input', () => {
192
- assert.throws(() => normalQuantile(-1), {
193
- message: 'p must be a decimal between 0 and 1'
194
- });
195
- });
196
-
197
- test('bad `p` > 1 input', () => {
198
- assert.throws(() => normalQuantile(2), {
199
- message: 'p must be a decimal between 0 and 1'
200
- });
201
- });
202
- });
203
- });