use case of modulo operator code example

Example 1: use case of modulo operator

function minutesToHours( m ) {
  hours = floor( m/60 );
  minutes = m%60;
    
  return "#hours# hours #minutes# minutes";
}
writeOutput( minutesToHours( 349 ) );

Example 2: use case of modulo operator

// given a list of widgets, files, people, etc.
longList = 10000; 
feedbackInterval = 100; // to be used as the modulus

// loop over the list to process each item
for( i=1; i <= longList; i++ ) {
	
  // perform some operation
	
  // mod operation gives feedback once every hundred loops
  if( i % feedbackInterval == 0 ) {
    percentCompleted = ( i / longList ) * 100;
    writeOutput( "#percentCompleted# percent complete. " );
  }
	
}

Example 3: use case of modulo operator

// array of options that we want to cycle through
weekdays = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri' ];

// option count provides modulus (divisor)
dayCount = weekdays.len();

employeeCount = 14;

// loop over employees while rotating through days
for( i=0; i < employeeCount; i++ ) {

  // employee number mod option count
  dayIndex = i % dayCount;
  // adjust because CFML array indexed from 1
  dayIndex++;
  // use result to cycle through weekday array positions
  weekday = weekdays[ dayIndex ];

  writeOutput( "Scheduling employee on #weekday#. " );
}

Tags:

Misc Example