Created
April 26, 2023 12:18
-
-
Save neall/9ed779774adb5c6dcfaf9d7e2fcd791b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function selectRandom(list, count) { | |
if (count < 1) return [] | |
const pickIndex = Math.floor(Math.random() * list.length) | |
const pick = list[pickIndex] | |
const remainder = list.filter((item, index) => index !== pickIndex) | |
const result = [pick].concat(selectRandom(remainder, count - 1)) | |
return result | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { strict as assert } from 'node:assert' | |
import selectRandom from './selectRandom.mjs' | |
const assertIncludes = (list, target) => { | |
assert(list.find(member => member === target)) | |
} | |
export const selectRandomTest = { | |
'returns the only result from a list of one': () => { | |
const a = Symbol('a') | |
const result = selectRandom([a], 1) | |
assert.equal(result.length, 1) | |
assert.equal(result[0], a) | |
}, | |
'returns all results from a list of three': () => { | |
const a = Symbol('a') | |
const b = Symbol('b') | |
const c = Symbol('c') | |
const result = selectRandom([a, b, c], 3) | |
assert.equal(result.length, 3) | |
assertIncludes(result, a) | |
assertIncludes(result, b) | |
assertIncludes(result, c) | |
}, | |
'returns two different results from a list of three': () => { | |
const result = selectRandom([Symbol(), Symbol(), Symbol()], 2) | |
assert.equal(result.length, 2) | |
assert.notEqual(result[0], result[1]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment