Closed
Description
As a consumer of the dartlang, it seems that more often than not I am given an object with some primary key attributes, such as an ID and want to get that Index to deal with CSS or set flags. Right now, the use cases I have seen is either:
int targetId = 5
var item = list.firstWhere((obj)=>obj.id == targetId, orElse: ()=>null;
var index = item==null? -1 : list.indexOf(item);
or:
int index = 0;
bool found = false;
for (var item in list) {
if (item.id == targetId) {
found = true;
break;
}
index++;
}
return found ? index : -1;
I have corrected my developers for using an ineffecient case (top) but thought it would be useful to implement a function for lists called: indexWhere
int indexWhere(func, {orElse: ()=> -1){
int index = 0;
bool found = false;
for (var item in list){
if (func(item)){
found = true;
break;
}
index ++;
}
return found ? index : fn();
}