Skip to content

Instantly share code, notes, and snippets.

@GoodNovember
Created September 24, 2018 21:27
Show Gist options
  • Save GoodNovember/b8b04229b1774e5fca84f29aca1360af to your computer and use it in GitHub Desktop.
Save GoodNovember/b8b04229b1774e5fca84f29aca1360af to your computer and use it in GitHub Desktop.
A Little Harsh
import shortId from "shortid"
export const HashToArray = (hash) => Object.keys(hash).map((key)=>hash[key])
export const ArrayToHash = (array) => array.reduce((acc, item)=>{
const {id} = item
acc[id] = item
return acc
},{})
export const Add = (hash, itemObject) => {
let { id } = itemObject
if(!id){ id = shortId.generate() }
const newItem = Object.assign({}, itemObject, {id})
const newHash = Object.assign({}, hash, {[id]:newItem})
return newHash
}
export const Remove = (hash, id) => {
const array = HashToArray(hash).filter((item)=>(item.id !== id))
const newHash = ArrayToHash(array)
return newHash
}
export const Update = (hash, id, updateObject) => {
if(hash[id]){
const alteredObj = Object.assign({}, hash[id], updateObject)
return Object.assign({}, hash, { [id]:alteredObj })
}else{
return hash
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment