Created
December 3, 2021 09:47
-
-
Save komalsdg/a3562087f4955445bc42d395c39b55c4 to your computer and use it in GitHub Desktop.
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
/* | |
#Task is to implement a function inventoryList such that: | |
#- it maintains the collection of all item names existing in an inventory, where each item is uniquely identified by a name. | |
#- returns a new object, with three methods: | |
# - add(name): the string name parameter is passed, and it is added to the collection. It is guaranteed that at any time, if an item is in the collection, then no longer item with the same name will be added to the collection. | |
# - remove(name): the string name parameter is passed, and this item is removed from the collection if it exists. If it does not exist, nothing happens. | |
# - getList(): this returns an array of names of items added so far. The names are returned in the order the corresponding items were added. | |
# Sample Case(s): | |
# 1) Input Output | |
# 5 Pineapple,Apple | |
# add Pineapple Apple | |
# add Apple | |
# getList | |
# remove Pineapple | |
# getList | |
# 2) Input Output | |
# 3 Pineapple | |
# add Pineapple | |
# remove Apple | |
# getList | |
function inventoryList() { | |
var items = []; | |
function add(item) { | |
if (item !== null){ | |
const index = items.indexOf(item); | |
if (index === -1){ | |
items.push(item); | |
} | |
} | |
} | |
function remove(item) { | |
const index = items.indexOf(item); | |
if (index > -1) { | |
items.splice(index, 1); | |
} | |
} | |
function getList() { | |
if (items){ | |
return items; | |
} else { | |
return null; | |
} | |
} | |
return { | |
add: add, | |
getList: getList, | |
remove: remove | |
}; | |
} | |
function main() { | |
const obj = inventoryList(); | |
const operationCount = 3; | |
let inputData = ['add Pineapple', 'remove Apple', 'getList']; | |
for(let k=1; k<= operationCount; k++) | |
{ | |
for(let i = 0; i < inputData.length; i++) { | |
const operationInfo = inputData[i].trim().split(' '); | |
if (operationInfo[0] === 'add') { | |
obj.add(operationInfo[1]); | |
} else if (operationInfo[0] === 'remove') { | |
obj.remove(operationInfo[1]); | |
} else if (operationInfo[0] === 'getList') { | |
const res = obj.getList(); | |
if (res.length === 0) { | |
console.log('No Items\n'); | |
} else { | |
console.log(`${res.join(',')}\n`); | |
} | |
} | |
} | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment