1// Copyright 2020 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/**
6 * @fileoverview Test random utilities.
7 */
8
9'use strict';
10
11const assert = require('assert');
12const sinon = require('sinon');
13
14const { twoBucketSample } = require('../random.js');
15
16const sandbox = sinon.createSandbox();
17
18
19describe('Two-bucket choosing', () => {
20  afterEach(() => {
21    sandbox.restore();
22  });
23
24  it('with one empty', () => {
25    sandbox.stub(Math, 'random').callsFake(() => 0.5);
26    assert.deepEqual([1, 2], twoBucketSample([0, 1, 2], [], 1, 2));
27    assert.deepEqual([1, 2], twoBucketSample([], [0, 1, 2], 1, 2));
28    assert.deepEqual([0], twoBucketSample([0], [], 1, 1));
29    assert.deepEqual([0], twoBucketSample([], [0], 1, 1));
30  });
31
32  it('chooses with 0.3', () => {
33    sandbox.stub(Math, 'random').callsFake(() => 0.3);
34    assert.deepEqual([1, 2], twoBucketSample([0, 1, 2], [3, 4, 5], 1, 2));
35    // Higher factor.
36    assert.deepEqual([3, 5], twoBucketSample([0, 1, 2], [3, 4, 5], 4, 2));
37  });
38
39  it('chooses with 0.7', () => {
40    sandbox.stub(Math, 'random').callsFake(() => 0.7);
41    assert.deepEqual([4, 3], twoBucketSample([0, 1, 2], [3, 4, 5], 1, 2));
42  });
43
44  it('chooses with 0.5', () => {
45    sandbox.stub(Math, 'random').callsFake(() => 0.5);
46    assert.deepEqual([3], twoBucketSample([0, 1], [2, 3, 4, 5], 1, 1));
47    assert.deepEqual([3], twoBucketSample([0, 1, 2, 3], [4, 5], 1, 1));
48    // Higher factor.
49    assert.deepEqual([4], twoBucketSample([0, 1, 2, 3], [4, 5], 2, 1));
50  });
51});
52