1

I'm creating a function that generate a random Uniq Serial id by replacing a string with this format ; xxxx-xxxx-xxxx-xxxx , the goal is to get a serial like that : ABCD-1234-EFGH-5678 ,the first and third parts are a letters and the second and last parts are numbers, this is my code :

public generateUniqSerial() {
   return 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, function (c) {
     let r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
     return v.toString(16)
   })
 }

it give a result like that : "7f8f-0d9a-fd5-450f" , how to edit this function to get a result with this format : ABCD-1234-EFGH-6789 ?

547n00n
  • 1,356
  • 6
  • 30
  • 55
  • Why do you want to make less unique Ids? – Rick McDonald Feb 19 '20 at 14:57
  • why not just use a package like uuid btw? – maxime1992 Feb 19 '20 at 15:04
  • 1
    Does this answer your question? [Create GUID / UUID in JavaScript?](https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript) – misha130 Feb 19 '20 at 15:26
  • Try this: `function generateUniqSerial() { return 'xxxx-aaaa-xxxx-aaaa'.replace(/[xa]/g, function(c) { var r = Math.random() * 16 | 0, v = (c == 'x' || c == 'a') ? r : (r & 0x3 | 0x8); return (c == 'x') ? String.fromCharCode((+v || 10) + 0x40) : v.toString(8).charAt(0); }) } console.log(generateUniqSerial());` – ferhado Feb 19 '20 at 16:07

2 Answers2

2

You can do something like this to generate a random Uniq Serial id with a format like ABCD-1234-EFGH-5678:

function rnd(t) {
  let str = '';
  const min = t === 'a' ? 10 : 0;
  const max = t === 'n' ? 10 : 62;
  for (let i = 0; i++ < 4;) {
    let r = Math.random() * (max - min) + min << 0;
    str += String.fromCharCode(r += r > 9 ? r < 36 ? 55 : 61 : 48);
  }
  return str;
}

function generateUniqSerial() {
  return `${rnd('a')}-${rnd('n')}-${rnd('a')}-${rnd('n')}`
}

console.log(generateUniqSerial())
console.log(generateUniqSerial())
palaѕн
  • 72,112
  • 17
  • 116
  • 136
0

When I'm asked to do things like this I like to start with a "string of letters" and a "string of digits." My logic then simply consists of choosing a random index into the appropriate source string to get each character that I need. I like to do it this way because to me it's "extremely obvious" what I am doing and equally easy to desk-check that it will work.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mike Robinson
  • 8,490
  • 5
  • 28
  • 41