* As above for an arbitrary number of elements with a fast implementation * for 1 or 2 elements.
(array, count)
| 98 | * for 1 or 2 elements. |
| 99 | */ |
| 100 | function sample(array, count) { |
| 101 | assert(count > 0); |
| 102 | assert(array.length >= count); |
| 103 | |
| 104 | // Fast paths for 1 or 2 elements. |
| 105 | if (count == 1) { |
| 106 | return [single(array)]; |
| 107 | } |
| 108 | if (count == 2) { |
| 109 | return sampleOfTwo(array); |
| 110 | } |
| 111 | |
| 112 | const copy = Array.from(array); |
| 113 | shuffle(copy); |
| 114 | return copy.slice(0, count); |
| 115 | } |
| 116 | |
| 117 | function shuffle(array) { |
| 118 | for (let i = 0; i < array.length - 1; i++) { |
no test coverage detected
searching dependent graphs…