Skip to content

Instantly share code, notes, and snippets.

@heygema
Created January 30, 2019 06:24
Show Gist options
  • Save heygema/5ff8d10f99e66b91ec6374cac4605a65 to your computer and use it in GitHub Desktop.
Save heygema/5ff8d10f99e66b91ec6374cac4605a65 to your computer and use it in GitHub Desktop.
db for bootcamp
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