Exercise: Warehouse Item

Practice how to implement a warehouse management program using the State pattern.

Problem statement

Imagine we’re working on a warehouse management program. Our next task is to create a class to model a warehouse item and help track it. Such a WarehouseItem class has a constructor, which accepts an id and the initial state of the item (which can be one of arriving, stored, or delivered). It has three public methods: 

  • store(locationId) moves the item into the stored state and records locationId where it’s stored. 

  • deliver(address) changes the state of the item to delivered, sets the delivery address, and clears locationId.

  • describe() returns a string representation of the current state of the item (for example, “Item 5821 is on its way to the warehouse,” or “Item 3647 is stored in location 1ZH3,” or “Item 3452 was delivered to John Smith, 1st Avenue, New York.” 

The arriving state can be set only when the object is created as it can’t be transitioned to from the other states. An item can’t move back to the arriving state once it’s stored or delivered, it can’t be moved back to stored once it’s delivered, and it can’t be delivered if it’s not stored first. Use the State pattern to implement the WarehouseItem class. 

Coding challenge

Write your solution code in the following code widget. We’ve already added the package.json file for your ease.

Get hands-on with 1200+ tech skills courses.