Reputation: 8297
I have a function called getItems
that returns an array of objects asynchronously. Each object has a isOccupied
method that returns a boolean.
I wrote a function that takes an index and returns whether index-th item in the array's isOccupied
is true or false.
I wrote a function to return the index of the item from the array returned by getItems
.
async getOccupiedItemIndex() {
let selectedIdx = 0;
return getItems().then(items => {
items.forEach((item, index) => {
if (item.isOccupied()) selectedIdx = index;
});
return selectedIndex;
});
}
I want to improve this function because
The fact that we are using an async
function to use an array makes it lengthy.
I see that if there is no item found, it could return null?
We can assume that there will only be one occupied item in the array.
Any thoughts on improving this?
Upvotes: 1
Views: 139
Reputation: 46121
Since you are in an async function, awaiting getIems
will simplify your logic, like so:
async function getOccupiedItemIndex() {
const items = await getItems();
let selectedIdx = null;
for (let i = 0; i < items.length; i++) {
if (items[i].occupied()) {
selectedIdx = i;
break;
}
}
return selectedIdx;
}
Upvotes: 0
Reputation: 365
You could use Array.findIndex() :
const getOccupiedItemIndex = () =>
getItems().then( items => items.findIndex( item => item.isOccupied() ) )
will find first occupied index or -1 if not found
Upvotes: 2
Reputation: 140
You could return the right variable. selectedIndex
isn't declared. Only selectedIdx
is.
Upvotes: 0