https://github.com/gpmcadam/swapsy
A simple, tiny, pure ES6 implementation of an array swap method
https://github.com/gpmcadam/swapsy
array es6 functional javascript pure swap swapsy tiny
Last synced: 5 months ago
JSON representation
A simple, tiny, pure ES6 implementation of an array swap method
- Host: GitHub
- URL: https://github.com/gpmcadam/swapsy
- Owner: gpmcadam
- License: mit
- Created: 2018-03-04T01:45:17.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-03-04T02:22:08.000Z (over 7 years ago)
- Last Synced: 2025-02-16T18:46:52.273Z (8 months ago)
- Topics: array, es6, functional, javascript, pure, swap, swapsy, tiny
- Language: JavaScript
- Size: 19.5 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README


Swap two elements in an array. Easy, peasy.
## Install
$ npm install swapsy
## Example
const swapsy = require('swapsy');
const arr = [ 'hello', 'world' ]
const fromIndex = 0
const toIndex = 1swapsy(arr, fromIndex, toIndex)
// Returns [ 'world', 'hello' ]
## Why?
- ✅ Tiny (~400 bytes)
- ✅ Zero-Dependencies
- ✅ Immutable/Pure
- ✅ ES6
- ✅ Tested## Better Example
Suppose you use React and Redux, and you have
some kind of action and a reducer that reorders
some components for the user.Your action might look like this:
const swapItems = (from, to) => {
return {
type: 'SWAP_ITEMS',
from,
to
}
}And your reducer might have looked like this:
const items = (state = [], ({ from, to })) => {
switch (action.type) {
case 'SWAP_ITEMS':
const x = state[from];
const y = state[to];
state[to] = x;
state[from] = y;
return state;
}
}Which is bad because it's long, ungainly, wasteful
and mutates the state directly. Also note, there are worse implementations than the one above.But with swapsy, keep your reducers pure and
readable:const swap = require('swapsy');
const items = (state = [], ({ from, to })) => {
switch (action.type) {
case 'SWAP_ITEMS':
return swap(state, from, to);
}
}