Generating Unique Ids For Each Expense#

Currently there is no way to uniquely identify an Expense object as we can create multiple objects that share the same label, amount, and date. To make Expense objects uniquely identifiable, we need to create a unique ID for each object and expose the ID through a getId() method.

In a consumer-facing application, we would most likely use a 3rd party library or service to handle ID creation. For FinanceMe, we will build our own utility.

The genUniqueId() utility function will be shared across the various entities of our application, so we place it in a shared location: the top-level utils folder, where we will place all global utilities:

The unique string returned from our utility can be broken down into two parts separated by a hyphen. For the first part, we use to get a numeric timestamp and convert this number into a base-36 string using Number.prototype.toString().

For the second half, we use Math.random() to generate a random number, convert that number to a base-36 string, and lastly truncate it to six characters using String.prototype.substring(). Notice that we start the substring at index 2 to skip over the decimal point in the resulting string. The end result is a function that produces a unique string whenever it is called with a very low probability of duplication.

Base-36 Numbers#

Base-36 (also called hexatridecimal) is a number system containing 36 distinct symbols. Compared to the decimal (base-10) number system that we are all familiar with, base-36 contains 0-9 as well as A-Z, allowing us to express large numbers more compactly using familiar symbols. For example, the number 1234 in base-10 can be represented as YA in base-36.

Using ts-node, we can test our new utility and observe the resulting strings:

Add genUniqueId to Expense#

We can now add a getId() method to our Expense class in three steps: add a private declaration for an id property, add a getId() method that returns the id property, and initialize the id property in the constructor:


This page is a preview of Beginners Guide to TypeScript

Start a new discussion. All notification go to the author.