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.
81 lines (51 loc) β’ 2.56 kB
Markdown
# π¦ array.mjs
A minimal and handy module offering a couple of focused utilities for working with arrays β from shuffling items randomly to generating smart sort functions for object arrays. Ideal for quick scripting or modular use in larger projects.
## `shuffleArray(items: string[]): string[]`
π 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).
- **items** β An array of strings to shuffle.
- **Returns** β The same array instance, but now shuffled.
### π 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.
You can find the original discussion here:
π https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
## π¦ `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