AnswerBun.com

Optimize these 4 methods in 1 method

Stack Overflow Asked by Singh on October 3, 2020

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.

One Answer

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,
  };
};

Correct answer by Dennis Vash on October 3, 2020

Add your own answers!

Related Questions

Substring instead of Left

2  Asked on January 5, 2021

   

R: Multi-type Point Pattern scan.test

1  Asked on January 5, 2021 by clemson

       

Pandas: filter rows with loc on anonymous dataframe

2  Asked on January 5, 2021 by user3579222

   

Why are the spacings in the decipher incorrect?

2  Asked on January 4, 2021 by iliketocode123465

   

How to play more than one stream at once using soundio?

1  Asked on January 3, 2021 by 010110110101

 

Units and Measurements in Swift

1  Asked on January 3, 2021 by tick_hoges

     

Count files in directory (python)

0  Asked on January 3, 2021 by user14606934

 

How to set the “Resource root URL” in Jenkins

1  Asked on January 3, 2021 by hephaestus

 

Write Pandas DataFrame to chronologic excel sheet

0  Asked on January 3, 2021 by anna-bleha

     

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP