https://github.com/wildhoney/moggy
Miniature ~2kb library that brings immutability to existing prototype functions employing the principle of least astonishment.
https://github.com/wildhoney/moggy
functional immutability immutable prototype side-effect tuples
Last synced: 2 months ago
JSON representation
Miniature ~2kb library that brings immutability to existing prototype functions employing the principle of least astonishment.
- Host: GitHub
- URL: https://github.com/wildhoney/moggy
- Owner: Wildhoney
- License: gpl-3.0
- Created: 2017-02-06T22:55:49.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2017-02-16T10:23:52.000Z (over 9 years ago)
- Last Synced: 2025-02-01T02:35:26.465Z (over 1 year ago)
- Topics: functional, immutability, immutable, prototype, side-effect, tuples
- Language: JavaScript
- Homepage:
- Size: 1.54 MB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README

> *moggy → transmogrify → "transform in a surprising or magical manner."*
> Miniature ~2kb library that brings immutability to existing prototype functions employing the [principle of least astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment).
[](http://forthebadge.com)
[](http://forthebadge.com)
## Getting Started
Moggy inspects the `prototype` of the value and creates an `object` that takes the functions from the prototype – it's therefore not easy to say *which* functions Moggy implements, since ECMAScript functions that mutate the value will respond with a tuple of `[sideEffect, returnValue]`, whereas functions that are already immutable in their nature will respond as-is.
```javascript
import m from 'moggy';
const a = m([1, 2, 3]);
const b = a.push(4);
const c = a.pop();
console.log(a); // [1, 2, 3]
console.log(b); // [sideEffect = [1, 2, 3, 4], returnValue = 4]
console.log(c); // [sideEffect = [1, 2], returnValue = 3]
```
In such cases it's not always obvious which value you may require – that's why Moggy returns both as a tuple. In the case of `push` you're more likely to require `sideEffect`, however in `pop` you're more likely to require the `returnValue`.
Using destructuring it's easy to take what you need – ignoring what you don't need.
```javascript
import m from 'moggy';
const a = m([1, 2, 3]);
const [b] = a.push(4);
const [, c] = a.pop();
console.log(a); // [1, 2, 3]
console.log(b); // [1, 2, 3, 4]
console.log(c); // 3
```