Created
January 30, 2019 06:24
-
-
Save heygema/5ff8d10f99e66b91ec6374cac4605a65 to your computer and use it in GitHub Desktop.
db for bootcamp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Products = Array<Product>; | |
export type Product = { | |
id: string; | |
name: string; | |
price: number; | |
photo: string; | |
}; | |
export type ProductEditInput = { | |
name: string; | |
price: number; | |
photo: string; | |
}; | |
let products: Products = [ | |
{id: '1', name: 'banana', price: 2000, photo: '...'}, | |
{id: '2', name: 'apple', price: 5000, photo: '...'}, | |
{id: '3', name: 'microsoft', price: 1200000, photo: '...'} | |
]; | |
type CreateDB = { | |
getItems: () => Array<Product>; | |
getItem: Function; | |
addItem: Function; | |
editItem: Function; | |
removeItem: Function; | |
}; | |
function createDB(): CreateDB { | |
let state = products; | |
function setState(newState) { | |
state = newState; | |
} | |
return { | |
getItems: () => state, | |
getItem: (id: string) => state.find(item => item.id === id), | |
addItem: (item: Product) => { | |
setState([...state, item]); | |
}, | |
editItem: (id: string, data: ProductEditInput) => { | |
let removedState = state.filter(i => i.id !== id); | |
let newItem = { | |
id, | |
name: data.name, | |
price: data.price, | |
photo: data.photo | |
}; | |
let newState = [...removedState, newItem]; | |
setState(newState); | |
}, | |
removeItem: (id: string) => { | |
let newState = state.filter(i => i.id !== id); | |
setState(newState); | |
} | |
}; | |
} | |
export default createDB; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment