remeda-extra/README.md

64 lines
2.1 KiB
Markdown
Raw Permalink Normal View History

2023-07-25 14:24:24 +00:00
# @yanick/remeda
2023-07-25 17:47:16 +00:00
This package provides a few functions to the already awesome
[remeda](https://remedajs.com/) library that I really want, but wasn't able to
get in Remeda itself.
2023-07-25 14:24:24 +00:00
2023-07-25 17:47:16 +00:00
## Usage
2023-07-25 14:24:24 +00:00
2023-07-25 17:47:16 +00:00
Just import the additional functions from `@yanick/remeda-extra`.
2023-07-25 14:24:24 +00:00
2023-07-25 17:47:16 +00:00
```
import { pipe } from 'remeda'; // as usual
import { matches } from '@yanick/remeda-extra'; // yanick-themed bonus feature!
2023-07-25 14:24:24 +00:00
```
## Additional functions
2023-07-25 15:25:50 +00:00
### `matches(target, matcher)`
### `matches(matcher)(target)`
2023-07-25 14:24:24 +00:00
Compares the input with the matcher and returns `true` if they match.
The matcher can be a function (which will be fed the input and is expected
to return a boolean), or a value. If the value is an object, the matching
will be recursive.
```
2023-07-25 17:47:16 +00:00
import { pipe } from 'remeda';
import { matches } from '@yanick/remeda-extra';
2023-07-25 14:24:24 +00:00
matches( 'potato', 'potato'); // => true
matches( 'potato', 'turnip'); // => false
matches( 'potato', vegetable => vegetable === 'potato'); // => true
matches({ a: 1, b :2 }, { a: 1 } ); // => true
matches({ 'a': 4, 'b': 5, 'c': 6 }, { 'a': 4, 'c': 6 }) // => true
pipe({a:1,b:2}, R.matches({ a: 1 }) ) // => true
pipe({a:1,b:2}, R.matches({ b: (val) => val < 5 }) ) // => true
pipe({a:1,b:2}, R.matches({ c: 3 }) ) // => false
pipe( { 'a': 4, 'b': 5, 'c': 6 }, R.matches({ 'a': 4, 'c': 6 })) // => true
```
2023-07-25 15:25:50 +00:00
### `sample(target, size | { size: number, repeating: boolean })`
### `sample(size | { size: number, repeating: boolean })(target)`
2023-07-25 17:47:16 +00:00
Like the `sample` that comes with Remeda, but this one shuffles its output
automatically.
2023-07-25 15:25:50 +00:00
Returns random elements of the array. If `size` is bigger than the array
length and `repeating` is false, returns a number of samples equal to
2023-07-25 17:47:16 +00:00
the size of the whole array.
2023-07-25 15:25:50 +00:00
```
sample([1,2,3,4],2); // [3,1]
sample([1,2,3,4],{size:5, repeating: true}); // [3,1,2,2,4]
sample([1,2,3,4],{size:5, repeating: false}); // [3,1,2,4]
R.pipe(
[{a: 5}, {a: 1}, {a: 3}],
R.sumBy(x => x.a)
) // 9
R.sample(2)([1,2,3,4]); // [3,1]
R.sample({size:5, repeating: true},[1,2,3,4]); // [3,1,2,2,4]
R.sample({size:5, repeating: false},[1,2,3,4]); // [3,1,2,4]
```