Singh
Singh

Reputation: 207

Optimize these 4 methods in 1 method

const getDate = (id) =>{
  const userId =  info.find(user => user.id === id)
  return userId.date;
 }

 const getValueAtOne = (id) => {
   const userId =  info.find(user => user.id === id)
   if(userId?.value[0]){
   return userId?.value[0]
   }
  
 }
 const getValueAtTwo = (id) => {
  const userId =  info.find(user => user.id === id)
   if(userId?.value[1]){ 
   return userId?.value[1]
   }
 
 }
 const getAllValues = (id) => {
  const userId =  info.find(user => user.id === id)
   if(userId?.value) {
   const arrValue = userId?.roles.map((validData) => {
     return { value: validData, label:validData };
   });
   return arrValue;
 }
 }

I have these 4 methods, which I am calling from different places in my code.But i want to optimize my code and want all these methods in a single method, but I cant figure out the best way to do it. first method returns me the date, second one returns the value of array at position 1, third method returns value of array at position 2, and 4th method returns the all the value and convert it in object.

Upvotes: 0

Views: 50

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53994

You can return a single object like so:

const getAll = (id) => {
  const userId = info.find((user) => user.id === id);

  const [valueAtOne, valueAtTwo] = userId?.value ?? [];

  const allValues =
    userId?.value.roles.map((validData) => ({
      value: validData,
      label: validData,
    })) ?? [];

  return {
    allValues,
    valueAtOne,
    valueAtTwo,
  };
};

Upvotes: 2

Related Questions