Coder Social home page Coder Social logo

swapsy's Introduction

swapsy.js

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 = 1

swapsy(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);
  }
}

swapsy's People

Contributors

gpmcadam avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.