Generating Unique Ids
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:
function genUniqueId(): string {
const dateStr = Date
.now()
.toString(36); // convert num to base 36 and stringify
const randomStr = Math
.random()
.toString(36)
.substring(2, 8); // start at index 2 to skip decimal point
return `${dateStr}-${randomStr}`;
}
export default genUniqueId;
The unique string returned from our utility can be broken down into two parts separated by a hyphen. For the first part, we use Date.now()
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 asYA
in base-36.
Using ts-node, we can test our new utility and observe the resulting strings:
import genUniqueId from './utils/genUniqueId';
// Note: your unique strings will differ from those below
genUniqueId(); // 'jyc9wbxw-wdk52s'
genUniqueId(); // 'jyc9wdka-0vc69r'
genUniqueId(); // 'jyc9wdwh-kb4k9l'
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:
import genUniqueId from '../utils/genUniqueId';
class Expense {
private label: string;
private amount: number;
private date: Date;
private id: string; // step 1: declare private property
constructor(label: string, amount: number, date: Date | string) {
this.updateLabel(label);
this.updateAmount(amount);
this.updateDate(date);
This page is a preview of Beginners Guide to TypeScript