Generating a unique serial ID using Angular/JS

I am in the process of developing a function that will create a unique serial id by replacing a string with the format; xxxx-xxxx-xxxx-xxxx. The desired outcome is a serial like this: ABCD-1234-EFGH-5678, where the first and third parts consist of letters and the second and last parts are numbers. Below is my current 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)
   })
 }

The above code gives a result similar to this: "7f8f-0d9a-fd5-450f". How can I modify this function to achieve the desired output in the format: ABCD-1234-EFGH-6789?

Answer №1

If you're looking to create a unique Serial ID with a specific format like ABCD-1234-EFGH-5678, you can use the following function:

function generateRandomSerial() {
  let serial = '';
  const minChar = 10; // ASCII value for characters after '9'
  const maxChar = 62; // Total number of alphanumeric characters
  for (let i = 0; i++ < 4;) {
    let randomNum = Math.random() * (maxChar - minChar) + minChar << 0;
    serial += String.fromCharCode(randomNum += randomNum > 9 ? randomNum < 36 ? 55 : 61 : 48);
  }
  return serial;
}

function generateUniqueSerialID() {
  return `${generateRandomSerial()}-${generateRandomSerial()}-${generateRandomSerial()}-${generateRandomSerial()}`
}

console.log(generateUniqueSerialID())
console.log(generateUniqueSerialID())

Answer №2

When given tasks like this, my preferred method is to begin with a "series of letters" and a "series of numbers." From there, I simply pick a random location within the designated source string to retrieve each necessary character. This approach appeals to me as it is clear and straightforward, making it effortless to verify its functionality through desk-checking.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery to send multiple values via an ajax request

I am looking to modify this script to send multiple values using AJAX instead of just a single value. files.php $(".search_button").click(function() { var search_word = $("#search_box").val(); var dataString = 'search_word='+ search_word ...

typescript encounters issues with union type while trying to access object properties

I'm puzzled by the errors I'm encountering in my IDE with the following code: I defined some interfaces/types interfaces/types: interface GradientColor { type: string; value: { angle: string | number; colours: string[]; }; } inte ...

Send a function as a parameter to another component, but it remains dormant

I am attempting to control the enable and disable state of a button based on changes in a value. To achieve this, I have defined a model as follows: export class Model{ label:string=''; isEnabled:Function=()=>true; } The component1 i ...

Simulating HTTP requests in end-to-end Protractor tests for Angular 4 application

We are currently working on a large project and have developed numerous test cases to cover various real-life user scenarios in our end-to-end functional tests. During testing, our application makes multiple REST calls to complete the test cases. When exe ...

Issue with Angular ngStyle toggle functionality not activating

I'm having an issue with toggling my navbar visibility on click of an image. It works the first time but not after that. Can anyone provide some assistance? Link to Code <img id="project-avatar" (click)="toggleNavbar()" width=20, height=20 style= ...

Nuxt - issue with updating window innerwidth getter

The class based components in our project utilize a getter to retrieve the window innerWidth. However, I've noticed that the value is only set once and doesn't update if the window width changes. get viewPortWidth() { if (process.client) { ...

Tips on accessing validator errors in Angular

Is there a way to extract the value from the 'minLength' validator error in order to use it in a message? This is my current HTML setup: <div class="mt-2" *ngIf="ngControl.control.errors?.minlength"> {{ &ap ...

Is there a way to reach a different function within the value of the react Context.Provider?

Right now, I am learning how to utilize the react context API. Within my react Provider class, I have some state data and functions stored in the value={}. But I am curious, how can I call a function inside this value from another function within the same ...

Sharing methods between two components on the same page in Angular can greatly improve code efficiency

On a single page, I have two components sharing some methods and properties. How can I utilize a service to achieve this? See the sample code snippet below... @Component({ selector: 'app', template: '<h1>AppComponent1</h1>' ...

React Component Fails to Refresh After Redux Modifications

I've recently started learning about React and Redux, and I've been trying to solve a particular issue for the past few days. The problem I'm facing is that my React component doesn't re-render when Redux updates. Despite seeing the st ...

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

An error occurs in TypeScript when attempting to reduce a loop on an array

My array consists of objects structured like this type AnyType = { name: 'A' | 'B' | 'C'; isAny:boolean; }; const myArray :AnyType[] =[ {name:'A',isAny:true}, {name:'B',isAny:false}, ] I am trying ...

No information retrieved from Ajax request

I've been utilizing the following jQuery code to execute an ajax call: $.ajax({ url: "/projects/project/xGetProjectStatus", type: "GET", dataType: "json"}) .done( function(request){ alert(request.responseText); ...

In production mode, the Angular/JS Express app is stuck in an endless routing loop, while it functions perfectly in development mode

My webapp is constructed using generator-angular-fullstack. While it functions properly in development mode (grunt serve), I encounter a problem with what appears to be an endless routing loop when switching to production mode (grunt serve:dist). The outp ...

Click to add a card

Attempting to incorporate a new row with the click of a button dynamically has proven to be challenging for me. As someone who is relatively new to JavaScript, I am struggling to figure it out. In the demonstration provided below, you will notice that noth ...

The connection between `this` and its calling context

Is all information from its call site accessible to a function? I was under the impression that a function would have access to the scope of its call site, but I could be mistaken. Any feedback and explanation would be greatly appreciated. function bar() ...

Using React hook form to create a Field Array within a Dialog component in Material UI

I have a form with custom fields added via Field Array from react-hook-form, and everything is functioning properly. However, I recently implemented drag and drop functionality for the property items to allow reordering them. Due to the large number of fie ...

determining the overall page displacement

I'm working with this code and I need help using the IF condition to check if the total page offset is greater-than 75%. How can I implement that here? function getLocalCoords(elem, ev) { var ox = 0, oy = 0; var first; var pageX, pageY; ...

organize and identify a JSON data using sorting and matching techniques

Having a JSON structure as shown below: [ { "id": "1", "freq": "1", "value": "Tiruchengode", "label": "Tiruchengode" }, { "id": "2", "freq": "1", "value": "Coimbatore", "label": " ...

Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page. Here is the c ...