Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
foundation/solutions/07_unit_testing/todo/todo.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
43 lines (36 sloc)
1012 Bytes
This file contains 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
'use strict' | |
let data = [] | |
module.exports.clear = () => { | |
data = [] | |
} | |
module.exports.add = (item, qty) => { | |
if (item === '') throw new Error('item cannot be empty') | |
if (qty === '') throw new Error('qty cannot be empty') | |
qty = Number(qty) | |
if(isNaN(qty)) throw new Error('qty must be a number') | |
let flag = false | |
for(const index in data) { | |
if (data[index].item === item) { | |
data[index].qty += qty | |
flag = true | |
} | |
} | |
if(flag === false) data.push({item: item, qty: qty}) | |
} | |
module.exports.getAll = () => { | |
for(const key in data) data[key].key = Number(key) | |
return data | |
} | |
module.exports.delete = key => { | |
console.log(`delete key ${key}`) | |
if (key === undefined) throw new Error('key cannot be undefined') | |
key = Number(key) | |
if (isNaN(key)) throw new Error('key must be a number') | |
try { | |
this.getAll()[key].key // throws error unless the item with the target key exists | |
data.splice(key, 1) | |
} catch { | |
throw new Error('key has to exist') | |
} | |
} | |
module.exports.countItems = () => data.length |