import find from 'lodash/find' ; import findLast from 'lodash/findLast' ; import findLastIndex from 'lodash/findLastIndex' ; import type { Moment } from 'moment-timezone' ; import type { BusSchedule , DepartureTimeList } from '../types' ; const isTruthy = ( x ) => Boolean ( x ) ; export type BusStateEnum = 'none' | 'before-start' | 'after-end' | 'running' | 'between-rounds' ; type ReturnVal = { status : BusStateEnum ; times : DepartureTimeList ; index : null | number ; nextStart ? : Moment ; } ; export function getCurrentBusIteration ( schedule , now ) { if ( schedule . times . length === 0 ) { return { status : 'none' , times : [ ] , index : null , nextStart : null } ; } let veryFirst = find ( schedule . times [ 0 ] , isTruthy ) ; let veryLast = findLast ( schedule . times [ schedule . times . length - 1 ] , isTruthy ) ; if ( ! veryFirst || ! veryLast ) { return { status : 'none' , times : [ ] , index : null , nextStart : null } ; } else if ( now . isBefore ( veryFirst ) ) { return { status : 'before-start' , times : [ ] , index : null , nextStart : veryFirst , } ; } else if ( now . isAfter ( veryLast ) ) { return { status : 'after-end' , times : [ ] , index : null , nextStart : null } ; } let index = findLastIndex ( schedule . times , ( stopTimes ) => { let first = find ( stopTimes , isTruthy ) ; let last = findLast ( stopTimes , isTruthy ) ; if ( ! first || ! last ) { return false ; } if ( now . isSameOrAfter ( first ) ) { return true ; } return false ; } ) ; if ( index !== - 1 ) { let times = schedule . times [ index ] ; let nextTimes = schedule . times [ index + 1 ] || [ ] ; let lastStopTime = findLast ( times , isTruthy ) ; let nextStart = find ( nextTimes , isTruthy ) ; if ( lastStopTime && nextStart && now . isBetween ( lastStopTime , nextStart ) ) { return { status : 'between-rounds' , times : nextTimes , index : index + 1 , nextStart , } ; } return { status : 'running' , times , index , nextStart } ; } return { status : 'none' , times : [ ] , index : null , nextStart : null } ; }