vendredi 4 août 2017

Need Better Solution for Simple JavaScript Pattern

I have rather verbose code for what seems like there must be a better solution:

I need to find the index of an array based on the object IDs. I originally had code as such:

idx = (state.store.addresses || []).findIndex(x => x.location == location_name)
if (idx > -1) { /* do something */}

But then I got the following error:

Uncaught (in promise) TypeError: Cannot read property 'addresses' of undefined

I figured that the short circuiting operator would cause it to jump to using the blank array [] upon an error like this, thus returning -1.


Because that solution didn't work, I'm wrapping up 8 of these statements in try...catch statements and this code is becoming long and verbose.

Is there any better way to handle this code other than the following?

try {
    idx = state.store.addresses.findIndex(x => x.location == location_name)
    state.store.addresses[idx]['deleted'] = false
    set(state.store.addresses[idx], 'deleted', false)
} catch (e) {}

try {
    idx = state.store.customer.addresses.findIndex(x => x.location == location_name)
    state.store.customer.addresses[idx]['deleted'] = false;
    set(state.store.customer.addresses[idx], 'deleted', false)
} catch (e) {}

// 5 more of these

Aucun commentaire:

Enregistrer un commentaire