Skip to content

Commit

Permalink
feat: add shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Oct 15, 2018
1 parent 4db9f7a commit d8b50a7
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ export { default as noop } from './noop'
export { default as parseCssValue } from './parseCssValue'
export { default as reduce } from './reduce'
export { default as repeat } from './repeat'
export { default as shuffle } from './shuffle'
export { default as supportPassiveEventListener } from './supportPassiveEventListener'
20 changes: 20 additions & 0 deletions src/shuffle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* 打乱一个数组。
*
* @param arr 要打乱的数组
* @returns 打乱后的数组
* @see https://gaohaoyang.github.io/2016/10/16/shuffle-algorithm/
*/
export default function shuffle<T>(arr: T[]): T[] {
if (!Array.isArray(arr)) {
return arr
}
const newArr = arr.slice()
for (let i = newArr.length - 1; i >= 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1))
const itemAtIndex = newArr[randomIndex]
newArr[randomIndex] = newArr[i]
newArr[i] = itemAtIndex
}
return newArr
}
23 changes: 23 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,3 +540,26 @@ describe('cssTransform', () => {
expect(el.style.transition).toBe('none')
})
})

describe('shuffle', () => {
test('非数组原样返回', () => {
expect(vtils.shuffle(1 as any)).toEqual(1)
expect(vtils.shuffle({} as any)).toEqual({})
expect(vtils.shuffle(false as any)).toEqual(false)
})
test('打乱数组', () => {
const arr1 = [1, 2, 3]
for (let i = 0; i < 1000; i++) {
expect([
[1, 2, 3],
[1, 3, 2],
[2, 1, 3],
[2, 3, 1],
[3, 1, 2],
[3, 2, 1]
]).toContainEqual(vtils.shuffle(arr1))
}
const arr2 = [1, 2, 3, '&', null, /x/, () => {}]
expect(vtils.shuffle(arr2).sort()).toEqual(arr2.sort())
})
})

0 comments on commit d8b50a7

Please sign in to comment.