Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided.

Input = "ABC DEF GHI"

The generated code would look like,

"ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters of the first word and the first letter of the rest). If that's also taken, then "ABCDG", following by "ABCDEG", and so on until a unique code is created. The validation process is done through an API call.

The inputs can vary:

"ABC" (or) "ABC DEF" (or) "ABC DEF GHI" (or) "ABC DEF GHI JKL"

I attempted the following approach:

let count = 1;

    let val = this.userForm.get("name").value;
    let textArr = val.split(" ");

    let res;
  
      for(let i = 0; i< textArr.length; i++){
    
         res += textArr[i].substring(0,count)
      
      }

      let char1 = "", char2 = "", char3 = "";
       
       let ss:any = val.split(" ", 3);
      
       if(ss[0].length > 1)
         char1 = ss[0].substring(0,2)
    
       if(ss[1] && ss[1].length > 0)
         char2 = ss[1].substring(0,1)
    
       if(ss[2] && ss[2].length > 0)
         char3 = ss[2].substring(0,1)
    
    let result = char1 + char2 + char3;

   this.restApi.validateCode(result).subscribe((data: any) => {
     console.log(data) // returns boolean
    });

I'm struggling to achieve the desired logic. Any suggestions?

Answer №1

Utilize this script to create a customized sequence in a specific order.

function generateCustomSequence(input)
{
  let sequence = [];
  
  let elements = input.split(" ").map(str => {return {str, index:1}});
  
  let item = elements.map(({str,index}) => str.substr(0,index)).join("");
  sequence.push(item);
  
  let element;
  while(element = elements.find(({str,index}) => index < str.length))
  {
    element.index++;
    item = elements.map(({str,index}) => str.substr(0,index)).join("");
    sequence.push(item);
  }
  
  return sequence;
}

console.log(generateCustomSequence("123"));
console.log(generateCustomSequence("123 456"));
console.log(generateCustomSequence("123 456 789"));
console.log(generateCustomSequence("123 456 789 101112"));

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

Processing ajax requests in Rails 4 using HTML format

I'm currently in the process of setting up ajax functionality for my contact form and I am currently testing to ensure that the ajax call is being made. When checking my console, I noticed that it is still being processed as HTML and I cannot seem to ...

Retrieving data response post upload with JQuery and an HTML5 Uploader

After uploading an image and receiving a successful post response with the id of the inserted image, how can I insert this response as a data-id attribute within a a tag? Where in the function does this process occur? Here is the function: function img_ ...

What is the best way to conduct tests on Typescript modules that are not intended for

Even though the compiler accepts my current solution without any errors, the tests are still failing with the message "ReferenceError: myFunction is not defined". I am interested in testing the functionality of the following module using TypeScript: File1 ...

Steps to programmatically update Node modules:

I am looking to incorporate the use of npm update within a script. Take a look at my code snippet below: var npm = require('npm'); npm.load(function () { npm.commands.outdated({json: true}, function (err, data) { //console.log(data); npm ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...

Receiving the error notification from a 400 Bad Request

I'm having trouble showing the errors returned from an API on my Sign up form when a user submits invalid data. You can check out the error response in the console here: console ss This is my approach in RegisterComponent.ts: onSubmit() { this.u ...

Retrieving information from a JSON web service can easily be done using just JavaScript and jQuery

I recently downloaded a sample application from the following URL: . I am pleased to report that the part I have implemented is functioning flawlessly: <script src="scripts/jquery-1.3.2.debug.js" type="text/javascript"></script> <script src ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

Mastering the Art of jQuery Post with Iteration and Result Utilization

I am facing an issue with my code function fetchInfoFromDB() { let body = ""; let text = ""; $("tr").each(function (index) { let code = $(this).children("td:nth-child(2)"); $.post("http://urltogetdatafromdatabase.com/getinfo.ph ...

Generating a client-side MD5 hash for an image file in order to compare it to the hash calculated by Firebase?

Is there a way to calculate the MD5 of an image file on the client side within my Angular Map application, that will match the MD5 when I store the file on Firestore? I need to verify that a user's file matches a reference version stored in Firebase ...

Interactive rotating display with constantly updating information

Recently I started learning angularJS and I must say, I am already hooked. I have developed a website that pulls data from JSON files (created by external scripts) locally to show real-time information on various pages. Now, I want to include a sliding car ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

Leveraging geoPosition.js in conjunction with colobox

How can I create a colorbox link that prompts the user for permission to access their location, and if granted, displays a map with directions from their current location? I've managed to get it partially working, but there's an issue when the us ...

React-Redux: Unable to access the 'closed' property as it is undefined

Encountered a problem when using dispatch() in React-Redux. Specifically, the action below: export const fetchMetrics = () => { dispatch(fetchMetricsBegin); APIService.get('/dashboard/info/') .then((response) => { ...

Setting the TypeScript version while initializing CDK

When creating a new CDK app in typescript, I typically use the following command: npx --yes <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9babdb299e8f7e8eae1f7eb">[email protected]</a> init app --language typesc ...

What is the best way to retrieve the second to last element in a list

When using Protractor, you have convenient methods like .first() and .last() on the ElementArrayFinder: var elements = element.all(by.css(".myclass")); elements.last(); elements.first(); But what about retrieving the element that comes right before the ...

Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows: for (var i = 0; i < length; i++) { $("div_" + (i + 1)).css("background-image", "../imageFile.png"); ...

I successfully made a GET request using Postman, but encountered an issue when trying to do the same request through a

Currently, my objective is to send URL encoded parameters through a GET request using the fetch function. To achieve this, I am attempting to display the parameters via Express in the following manner: app.get('/api', function (req, res) { c ...

Creating a basic bootstrap modal dialog in ASP.NET MVC: A step-by-step guide

After navigating from the login page, the user clicks on the "ForgotPassword" link and is directed to a separate page where they can fill out a form to request a new password. http://localhost:2350/Account/ForgotPassword Once the user clicks on the "Save ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...