Skip to content

Commit

Permalink
Add randomFromObject function
Browse files Browse the repository at this point in the history
  • Loading branch information
ericyd committed Jan 18, 2024
1 parent 013fa77 commit 9d1355e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,14 @@ export function randomFromArray(array, rng = Math.random) {
const index = randomInt(0, array.length, rng)
return array[index]
}

/**
* Returns a random value from an object
* @template T
* @param {Record<string, T>} obj
* @param {Rng} rng
* @returns {T}
*/
export function randomFromObject(obj, rng = Math.random) {
return obj[randomFromArray(Object.keys(obj), rng)]
}
20 changes: 20 additions & 0 deletions lib/random.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import assert from "node:assert"
import { describe, it } from "node:test"
import { randomFromObj } from './random.js'


describe('randomFromObj', () => {
it('returns a value from the object', () => {
const obj = { a: 1, b: 2, c: 3 }
const rng = () => 0.5
assert.strictEqual(randomFromObj(obj, rng), 2)
})
})

describe('randomFromArray', () => {
it('returns a value from the object', () => {
const arr = [1,2,3]
const rng = () => 0.5
assert.strictEqual(randomFromArray(arr, rng), 2)
})
})

0 comments on commit 9d1355e

Please sign in to comment.