Bambang M
Bambang M

Reputation: 1

How to make unique id?

I want to make a unique id is like this :

id prefix uniqueid
1 pm pm-1
2 ad ad-1

The problem is If i want to add some data where have prefix "ad" the result must

id prefix uniqueid
1 pm pm-1
2 ad ad-1
3 ad ad-2

So the result must ad-2, ad-3 , ad-4 and go on if we add pm so the result must pm-2, pm-3 and go on

I trying to make "table helper" to me but it will be too much table

There's any idea to solve this ? I use postgres and node js ~

Upvotes: 0

Views: 100

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could take an object with prefix as key for latest id.

const
    add = (ids => prefix => `${prefix}-${ids[prefix] = (ids[prefix] || 0) + 1}`)
          ({});
    
console.log(add('ad'));
console.log(add('ad'));
console.log(add('pm'));
console.log(add('pm'));
console.log(add('ad'));

Upvotes: 1

Related Questions