News for hackers. Stuff that matters.
Re:Use labels to break ifs in JavaScript by cdumler on Wednesday August 07, 2013 @10:49AM (#6173195)
The reason to use it when you have a lot of conditional behavior tied to processing that can stop a process. With traditional code you have really two choices: highly-nested conditionals (or lots of utility subroutines) or using thrown errors for process control (which isn't their purpose). With labels, you're using process control for process control. In my experience, labels generally come into play for data processing, where often the desired behavior is not known until substantial decoding occurs. For made-up instance:

  var rec = dataStream.next()  // Stream sorted by lastName 
  processAtoM: while(rec) {
    
    // Stop at N's
    var lastName = rec.person.lastName.toUpperCase();
    if(lastName === 'N') break processingLoop;

    processRecord: do {
      // We don't want deleted records.
      if(rec.deleted === true) break processRecord;

      // We don't want employee senior management, contractors or founders.
      var employeeType = Persistence.employeeType.find(rec.company.employeeType);
      if(['senior management', 'contractor', 'founder'].indexOf(employeeType) !== -1) break processRecord;

      // Management was never sane about history structures.. FML
      var history = someWackyDataStructureProcessThatIsPrettyIntensive(rec);
      
      // At least I can be functional with this part.
      var totalPromotions = _.reduce(history, function(total, item) {
        if(item.promoted || item.lastPromotion !== undefined) {
          total += 1;
        }
        return total;
      }, 0);
 
      // After people with 2 or more promotions
      if(totalPromotions < 2) break processRecord;

      // More conditions..

      // Finally, this is still an interesting record.
      var outputRec = someFormattingProcessToOutputFormat(rec);
      outputStream.write(outputRec);

    } while (false);
    rec = dataStream.next();
  }

There are no comments on this comment yet.