tiny-essentials
Version:
Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.
108 lines (70 loc) โข 2.97 kB
Markdown
# ๐ฆ array.mjs
A tiny utility for shuffling arrays using the good old FisherโYates algorithm. Simple, efficient, and perfectly random (as far as JavaScript's `Math.random()` allows, anyway).
## โจ Features
- ๐ Uses the classic **FisherโYates** algorithm
- ๐ Shuffles arrays **in-place**
- ๐ฏ Guarantees **uniform distribution** of permutations
- ๐ Well-documented and easy to read
- ๐งช No dependencies โ just plug and play
## ๐ Usage
```js
import { shuffleArray } from './array.mjs';
const fruits = ['apple', 'banana', 'cherry', 'date'];
shuffleArray(fruits);
console.log(fruits); // ['banana', 'cherry', 'apple', 'date'] (order will vary)
```
> Note: The original array is shuffled in place. If you want to preserve the original order, make a copy before shuffling.
## ๐ง How It Works
This function implements the **FisherโYates shuffle** (also known as the Knuth shuffle), which runs in linear time and guarantees uniform randomness:
```js
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[items[currentIndex], items[randomIndex]] = [items[randomIndex], items[currentIndex]];
}
```
You can find the original discussion here:
๐ https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
## ๐ API
### `shuffleArray(items: string[]): string[]`
- **items** โ An array of strings to shuffle.
- **Returns** โ The same array instance, but now shuffled.
# ๐ฆ `arraySortPositions`
๐ง **Generates a comparator function** to sort an array of objects by a specified key, with optional reverse order.
## ๐ Function Signature
```js
arraySortPositions(item: string, isReverse?: boolean): (a: Object<string|number, *>, b: Object<string|number, *>) => number
```
## ๐ง Parameters
| Name | Type | Default | Description |
| ----------- | --------- | ------- | ---------------------------------------------------------- |
| `item` | `string` | โ | ๐ The key to sort the objects by. |
| `isReverse` | `boolean` | `false` | ๐ If `true`, the sorting will be in **descending** order. |
## ๐ฏ Returns
๐งฉ A **comparator function** compatible with `Array.prototype.sort()`:
```js
(a, b) => number
```
It compares two objects based on the specified `item` key.
## ๐ก Examples
```js
const arr = [{ pos: 2 }, { pos: 1 }, { pos: 3 }];
arr.sort(arraySortPositions('pos'));
// ๐ผ Ascending: [{ pos: 1 }, { pos: 2 }, { pos: 3 }]
```
```js
const arr = [{ pos: 2 }, { pos: 1 }, { pos: 3 }];
arr.sort(arraySortPositions('pos', true));
// ๐ฝ Descending: [{ pos: 3 }, { pos: 2 }, { pos: 1 }]
```
## ๐ ๏ธ Use Case
Great for situations where you need to **dynamically sort objects** by one of their keys, such as:
* Sorting users by age
* Ordering tasks by priority
* Displaying leaderboard scores