easierbycode
6/10/2013 - 4:48 AM

defineGetter

defineGetter

function Trip(startTime) {
  this.startTime = startTime != null ? startTime : new Date().getTime();

  this.__defineGetter__('startInWords', function (){
    var diff = (((new Date()).getTime() - (new Date(this.startTime)).getTime()) / 1000)
      , dayDiff = Math.floor(diff / 86400);
      
      return dayDiff == 0 && (
        diff < 60 && 'just now' ||
        diff < 120 && '1 minute ago' ||
        diff < 3600 && Math.floor( diff / 60 ) + ' minutes ago' ||
        diff < 7200 && '1 hour ago' ||
        diff < 86400 && Math.floor( diff / 3600 ) + ' hours ago')
      ||
        dayDiff == 1 && 'Yesterday' ||
        dayDiff < 7 && dayDiff + ' days ago' ||
        Math.ceil( dayDiff / 7 ) + ' weeks ago';
  })
}

myTrip = new Trip();
tenDaysAgoTime = new Date().getTime() - ((86400 * 10) * 1000);
tenDaysAgoTrip = new Trip(tenDaysAgoTime);

console.log(myTrip.startInWords);  // just now
console.log(tenDaysAgoTrip.startInWords);  // 2 weeks ago (1.N is rounded up by Math.ceil)
Trip = (startTime) ->
  @startTime = (if startTime? then startTime else new Date().getTime())
  @__defineGetter__ "startInWords", ->
    diff = (((new Date()).getTime() - (new Date(@startTime)).getTime()) / 1000)
    dayDiff = Math.floor(diff / 86400)
    dayDiff is 0 and (diff < 60 and "just now" or diff < 120 and "1 minute ago" or diff < 3600 and Math.floor(diff / 60) + " minutes ago" or diff < 7200 and "1 hour ago" or diff < 86400 and Math.floor(diff / 3600) + " hours ago") or dayDiff is 1 and "Yesterday" or dayDiff < 7 and dayDiff + " days ago" or Math.ceil(dayDiff / 7) + " weeks ago"

myTrip = new Trip()
tenDaysAgoTime = new Date().getTime() - ((86400 * 10) * 1000)
tenDaysAgoTrip = new Trip(tenDaysAgoTime)

console.log myTrip.startInWords  # just now
console.log tenDaysAgoTrip.startInWords  # 2 weeks ago (1.N is rounded up by Math.ceil)