| 1 | const mwExperiments = mw.experiments; |
| 2 | /* |
| 3 | * Bucketing wrapper for creating AB-tests. |
| 4 | * |
| 5 | * Given a test name, sampling rate, and session ID, provides a class that buckets a user into |
| 6 | * a predefined bucket ("unsampled", "control", or "treatment") and starts an AB-test. |
| 7 | */ |
| 8 | const bucket = { |
| 9 | UNSAMPLED: 'unsampled', // Old treatment: not sampled and not instrumented. |
| 10 | CONTROL: 'control', // Old treatment: sampled and instrumented. |
| 11 | TREATMENT: 'treatment' // New treatment: sampled and instrumented. |
| 12 | }; |
| 13 | |
| 14 | /** |
| 15 | * Buckets users based on params and exposes an `isSampled` and `getBucket` method. |
| 16 | * |
| 17 | * @ignore |
| 18 | * @param {Object} config Configuration object for AB test. |
| 19 | * @param {string} config.testName |
| 20 | * @param {number} config.samplingRate Sampling rate for the AB-test. |
| 21 | * @param {number} config.sessionId Session ID for user bucketing. |
| 22 | * @constructor |
| 23 | */ |
| 24 | function AB( config ) { |
| 25 | const testName = config.testName; |
| 26 | const samplingRate = config.samplingRate; |
| 27 | const sessionId = config.sessionId; |
| 28 | const test = { |
| 29 | name: testName, |
| 30 | enabled: !!samplingRate, |
| 31 | buckets: { |
| 32 | unsampled: 1 - samplingRate, |
| 33 | control: samplingRate / 2, |
| 34 | treatment: samplingRate / 2 |
| 35 | } |
| 36 | }; |
| 37 | |
| 38 | /** |
| 39 | * Gets the users AB-test bucket. |
| 40 | * |
| 41 | * A boolean instead of an enum is usually a code smell. However, the nature of A/B testing |
| 42 | * is to compare an A group's performance to a B group's so a boolean seems natural, even |
| 43 | * in the long term, and preferable to showing bucketing encoding ("unsampled", "control", |
| 44 | * "treatment") to callers which is necessary if getBucket(). The downside is that now two |
| 45 | * functions exist where one would suffice. |
| 46 | * |
| 47 | * @private |
| 48 | * @return {string} AB-test bucket, `bucket.UNSAMPLED` by default, `bucket.CONTROL` or |
| 49 | * `bucket.TREATMENT` buckets otherwise. |
| 50 | */ |
| 51 | function getBucket() { |
| 52 | return mwExperiments.getBucket( test, sessionId ); |
| 53 | } |
| 54 | |
| 55 | function isControl() { |
| 56 | return getBucket() === bucket.CONTROL; |
| 57 | } |
| 58 | |
| 59 | function isTreatment() { |
| 60 | return getBucket() === bucket.TREATMENT; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Checks whether or not a user is in the AB-test, |
| 65 | * |
| 66 | * @private |
| 67 | * @return {boolean} |
| 68 | */ |
| 69 | function isSampled() { |
| 70 | return getBucket() !== bucket.UNSAMPLED; // I.e., `isControl() || isTreatment()` |
| 71 | } |
| 72 | |
| 73 | return { |
| 74 | isControl: isControl, |
| 75 | isTreatment: isTreatment, |
| 76 | isSampled: isSampled |
| 77 | }; |
| 78 | } |
| 79 | |
| 80 | module.exports = AB; |