Skip to content

concept of List.indexWhere functionality #30275

Closed
@fallenreaper

Description

@fallenreaper

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();
    }

Metadata

Metadata

Assignees

Labels

area-core-librarySDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.core-2library-coretype-enhancementA request for a change that isn't a bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions