@guj/rif-js
Version:
Simplify filter,map and such when their use should be conditionnal
91 lines (75 loc) • 2.99 kB
Markdown
# Rif.js
Rif is a "simple" lib with a "simple" syntax meant to simplify certain operations.
## contains (as of today) :
`filterIf` ; `mapIf` ; `concatIf` ; `sliceIf`
## TL;DR
Turn :
```js
myArray
.filter(elem => {
if(aCondition){
return true;
}
return checkSomethingOnElement(elem);
})
.forEach(doSomethingToElement);
```
Into:
```js
Rif.of(myArray)
.filterIf(aCondition)(checkSomethingOnElement)
.forEach(doSomethingToElement);
```
## An example from the everyday life
### State of the art :
Let's say you have a huge bunch of kids but just lost your job, the most reasonable thing to do would be to [sell them all for pharmaceutical research](https://www.youtube.com/watch?v=bzVHjg3AqIQ 'Catholics views on birth control as, satirically, depicted by the Monthy Pythons in their movie: "The meaning of life" which I, most sincerely, recommend you to watch ASAP If you had not yet.') wouldn't it ?
Now, let's assume that you plan this using JS (and why not) this might look like this:
```js
arrayOfKids.forEach(sendToLab); // Haaa ... so nice and concise :D
```
But, suddenly, you receive a call for a part-time job, your new salary (quite conveniently for my point) allows you to provide (exactly) for you, your life-partner and those of your kids that haven't been naughty.
This may end up looking like this:
```js
arrayOfKids
.filter(isThisKidNaughty)
.forEach(sendToLab);
/* That, actually, is still pretty nice */
```
Then you remember that:
- given your lack of access to planned parenthood
- you're bound to have too many kids again
- given the current economy/state of the labor-protection
- you're bound to loose thy job again
So you prepare the code so that it works every time :
```js
arrayOfKids
.filter(kid => isThisKidNaughty(kid)||!iHaveEnoughIncomeToKeepNiceKids) // ewww !
.forEach(sendToLab);
```
That's a oneliner but that is not "first glance" clear to everyone so you try to make it more expressive:
```js
arrayOfKids
.filter(kid => {
if(!iHaveEnoughIncomeToKeepNiceKids){
return true;
}
return isThisKidNaughty(kid);
})
.forEach(sendToLab);
```
Not that much better.
### Now with Rif :
```js
Rif.of(arrayOfKids)
.filterIf(!iHaveEnoughIncomeToKeepNiceKids)(isThisKidNaughty)
.forEach(sendToLab);
```
## Bonus :
Rif.js is dynamically built so any addition to `Array.prototype` in the future will be "If-ed" automatically.
For example, if tomorrow, you have a method `respectfulReverse()` that would be like `reverse` but instead of modifying the original, it returns a new array, that method will have it's if without changing code or lib version.
## Other Bonus :
I have some ideas about things I could do next but am too lazy to put up a roadmap. And if YOU have an idea, put an issue or (even better) a PR.
## Remarkable feedbacks :
> That's brilliant ! I wish I'd have had that years ago.
>
> -- <cite>me</cite>