0

I want to create a function which takes an input and returns an incremented Id each time it is called.

Something like:

  function createId(input){
    let initialValue = 1
    let newId = `ID-${initialValue++}`
    return newId

So here in this function I will pass input as 'xyz', 'abc', etc based on which it should return an Id.

Like: If I am passing 'xyz' then it should return newId as Id-1 then Id-2 then Id-3 each time the function is called with xyz, Similarly, each time function is called with 'abc' it should return newId as Id-1, Id-2, Id-3.

I am Unable to create the ID based on inputs given. Thank you

2 Answers 2

1

Make an object which counts up how many times the function has been called with a particular string so far:

const inputCounts = {};
function createId(input){
  inputCounts[input] = (inputCounts[input] || 0) + 1;
  return `ID-${inputCounts[input]}`;
}
console.log(createId('foo'));
console.log(createId('foo'));
console.log(createId('foo'));
console.log(createId('bar'));

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @CertainPerformance. Totally works. Accepting in 8min
The Id repeats itself from 1 once it's closed and reopened. Actually I am storing the value in mongoDB. Is there a better way I can do so?
0

You can use session storage. Initially check if curr a key to session storage exists. If it exist then get it's value increment it , add it to id and update the value is session storage. If it does not exit then create a key and update it

function createId(input){
   let newId;
   if(!sessionStorage.currId){
     sessionStorage.setItem('currId',1);
     newId = `ID-1`
    }
    else{
     const newIncrementedVal = parseInt(sessionStorage.currId,10)+1;
     newId = ID-${initialValue++}
    }
    return newId
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.