Skip to content

Commit 3d5ef2b

Browse files
committed
✨ sampleSize
1 parent d3a29dd commit 3d5ef2b

File tree

4 files changed

+26
-2
lines changed

4 files changed

+26
-2
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { sampleSize } from '..'
2+
3+
test('sampleSize', () => {
4+
console.log(sampleSize([1, 2, 3], 2))
5+
console.log(sampleSize([1, 2, 3], 3))
6+
console.log(sampleSize([1, 2, 3], 4))
7+
console.log(sampleSize([1, 2, 3, 4, 5], 3))
8+
console.log(sampleSize([1, 2, 3, 4, 5], 4))
9+
})

src/collection/groupBy.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
export const groupBy = (arr, fn = x => x) =>
77
arr.reduce((res, el) => {
88
const foo = typeof fn === 'function' ? fn(el) : el[fn]
9-
if (res[foo]) res[foo].push(el)
10-
else res[foo] = [el]
9+
res[foo] = res[foo] || []
10+
res[foo].push(el)
1111
return res
1212
}, {})

src/collection/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './countBy'
22
export * from './groupBy'
3+
export * from './sampleSize'

src/collection/sampleSize.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Gets n random elements at unique keys from collection up to the size of collection.
2+
3+
// TODO:
4+
5+
export const sampleSize = (nums, n = 1) => {
6+
const foo = [...nums]
7+
const len = n > nums.length ? nums.length : n
8+
9+
let res = []
10+
for (let i = 0; i < len; i++) {
11+
res.push(...foo.splice(Math.round(Math.random() * (len - 1 - i)), 1))
12+
}
13+
return res
14+
}

0 commit comments

Comments
 (0)