Created
March 27, 2014 22:47
-
-
Save bryanaka/9820803 to your computer and use it in GitHub Desktop.
rough group by time range computed property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Ember.computed.groupByTimeRange = (dependantArrayKey, dependantChildKey, hourRange) -> | |
dependantProperty = "#{dependantArrayKey}.@each.#{dependantChildKey}" | |
Em.computed( -> | |
# hash by dates | |
activityItemsHash = {} | |
activityItems = @get(dependantArrayKey).sortBy(dependantChildKey) | |
groupedActivityItems = [] | |
activityItems.forEach (activity, index, activities) => | |
hashPosition = null | |
activityTime = activity.get(dependantChildKey) | |
# iterate to find correct hash key. | |
for own lowerTimeLimit of activityItemsHash | |
# hash keys define the lower time limits | |
# needs to be converted back to date for comparison | |
lowerTimeLimit = new Date(lowerTimeLimit) | |
# create and set upper time limit | |
upperTimeLimit = new Date(lowerTimeLimit.getTime()) | |
upperTimeLimit.setHours(upperTimeLimit.getHours() + hourRange) | |
if lowerTimeLimit <= activityTime and upperTimeLimit >= activityTime | |
hashPosition = lowerTimeLimit | |
break | |
hashPosition ||= activityTime | |
# if that position is already an array, push the activity | |
if Em.isArray(activityItemsHash[hashPosition]) | |
activityItemsHash[hashPosition].pushObject(activity) | |
# if that position is populated but only has one item | |
else if !Em.isNone(activityItemsHash[hashPosition]) | |
# extend and use array proxy to something that has the child dependant key | |
activityItemsHash[hashPosition] = Ember.ArrayProxy.create({content: [activityItemsHash[hashPosition], activity]}) | |
# if it doesn't fit any range | |
else | |
activityItemsHash[hashPosition] = activity | |
# convert activity Items hash into an array | |
for own key, group of activityItemsHash | |
groupedActivityItems.pushObject(group) | |
return groupedActivityItems | |
).property(dependantProperty) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment