shuffle
collection
Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.
Installation
Import
import { shuffle } from '@tulx/utils';Source Code
Implementation
/**
* Creates an array of shuffled values, using a version of the Fisher-Yates shuffle.
*
* @param collection - The collection to shuffle.
* @returns Returns the new shuffled array.
*
* @example
* ```ts
* shuffle([1, 2, 3, 4]); // [4, 1, 3, 2] (random)
* ```
*/
export function shuffle<T>(collection: readonly T[] | Record<string, T>): T[] {
const items = Array.isArray(collection)
? [...collection]
: Object.values(collection);
const result = [...items];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
Example
import { shuffle } from '@tulx/utils';
shuffle([1, 2, 3, 4]); // [4, 1, 3, 2] (random)Related Functions
countBy
Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
each
Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).
eachRight
This method is like each except that it iterates over elements of collection from right to left.
every
Checks if predicate returns truthy for all elements of collection.
filter
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
find
Iterates over elements of collection, returning the first element predicate returns truthy for.