1

I have an array object called containtemps. It has a property value called modDate.

I extract the boolean value of the temperror variable by comparing the time based on the modDate property value among several objects in containtemps.

So, by putting temperror variables 1, 2, and 3 in the error variable, if any one of them is true, the NotError component is rendered, and when all of them are false, the Error component is rendered.

But looking at my code, this seems inefficient because there are too many duplicates.

As you can see, temperror0 and temperror1 and temperror2, The code that creates the variable is duplicated. How can I get rid of these duplicate values ​​in one piece of code?

this is my code

    const containtemps = [
        {
            modDate:"2022-09-22T04:48:00.000Z"
        },
        {
            modDate: null
        },
        {
            modDate:"2022-09-22T04:5:00.000Z"
        }
    ]

      this is duplicated code

      let curTime = new Date()
      curTime.setHours(curTime.getHours() - 6)


    const tempModate0 = containtemps[0]?.modDate;

    let tempmodDate0 = new Date(tempModate0)

    let temperror0 = curTime.getTime() <= tempmodDate0.getTime() ? false : true


    const tempModate1 = containtemps[1]?.modDate;


    let tempmodDate1 = new Date(tempModate1)

    let temperror1 = curTime.getTime() <= tempmodDate1.getTime() ? false : true



    
    const tempModate2 = containtemps[2]?.modDate;


    let tempmodDate2 = new Date(tempModate2)

    let temperror2 = curTime.getTime() <= tempmodDate2.getTime() ? false : true

    const error =

    temperror0 ||
    temperror1 ||
    temperror2 ;

    ;


    return (

    !error ?
    (
    <NotError>
    notError
    </NotError>

    )
    :
    (
        <Error>
        error
        </Error>)

    )
1
  • Side note: There's no reason for the conditional operator in curTime.getTime() <= tempmodDate0.getTime() ? false : true. Just use curTime.getTime() > tempmodDate0.getTime() instead. Commented Sep 22, 2022 at 6:10

1 Answer 1

1

You can use some function inside your array. It will return true if it finds at least one result matching your expression. Here you need the opposite expression >

const curTime = new Date();
const error = containtemps.some(t => t.modDate && curTime.getTime() > new Date(t.modDate).getTime())
Sign up to request clarification or add additional context in comments.

4 Comments

thank you but it doesn't match
curTime is the current time?
ah sorry is like this let curTime = new Date() curTime.setHours(curTime.getHours() - 6)
but it sames...

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.