Created
August 6, 2013 20:59
-
-
Save KarlPurk/6168582 to your computer and use it in GitHub Desktop.
Combine elements of an array, optionally summing specified properties. Written in ObjectScript.
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
Class App.ArrayCombineSum Extends %RegisteredObject | |
{ | |
ClassMethod createKey(array, keys) As %String | |
{ | |
set output = "" | |
set index = keys.Next("") | |
while (index) { | |
set key = keys.GetAt(index) | |
set value = array.GetAt(key) | |
if (value'="") { | |
set output=output_array.GetAt(key) | |
} | |
set index = keys.Next(index) | |
} | |
quit output | |
} | |
ClassMethod arrayCombineSum(ByRef data As %ListOfDataTypes, keys As %ListOfDataTypes, sumProperties As %ListOfDataTypes) | |
{ | |
set identityMap = ##class(%ArrayOfDataTypes).%New() | |
set output = ##class(%ListOfDataTypes).%New() | |
set key = data.Next("") | |
while (key) { | |
set item = data.GetAt(key) | |
set pk = ..createKey(item, keys) | |
if (identityMap.GetAt(pk)="") { | |
do identityMap.SetAt(item,pk) | |
do output.Insert(item) | |
} | |
else { | |
set existingItem = identityMap.GetAt(pk) | |
set sumPropertiesIndex = sumProperties.Next("") | |
while (sumPropertiesIndex) { | |
set sumPropertiesKey = sumProperties.GetAt(sumPropertiesIndex) | |
set itemValue = item.GetAt(sumPropertiesKey) | |
set existingItemValue = existingItem.GetAt(sumPropertiesKey) | |
set newValue = itemValue + existingItemValue | |
do existingItem.SetAt(newValue, sumPropertiesKey) | |
do identityMap.SetAt(existingItem, pk) | |
set sumPropertiesIndex = sumProperties.Next(sumPropertiesIndex) | |
} | |
} | |
set key = data.Next(key) | |
} | |
set data = output | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment