Quote:
Originally Posted by Inverness
If...
|
Anyhow...
I made an addition to my TMap set. For those of you who want to use it, I've made a static function for it:
class_tmap_static (Class)
PHP Code:
public function merge( map1, map2, mergeRules )
{
// Sanity Check
if ( !map1.instanceOf( TMap ) || !map2.instanceOf( TMap ))
{
echo("Input aren't TMaps!");
return null; // Force programmer to input CORRECT Data!
}
// Change Merger to supplied one
temp.oldMerger = this.mergeValue;
if ( mergeRules != null )
this.mergeValue = mergeRules;
// Copy first Map to a new map
temp.sum = this.newInstance( map1.toArray() );
temp.keys = temp.sum.keySet();
// Add second map to new map
temp.mapSet = map2.toArray();
for ( temp.mapValue: temp.mapSet )
{
// If new map contains given key
if ( temp.mapValue[0] in temp.keys )
{
// Merge them together
temp.newValue = mergeValue(
temp.mapValue[0], // key
temp.mapValue[1], // val1
temp.sum.get( temp.mapValue[0] ) // val2
);
temp.sum.put( temp.mapValue[0], temp.newValue );
} else {
// Otherwise, put second map data to the new map.
temp.sum.put( temp.mapValue[0], temp.mapValue[1] );
}
}
// Revert back to old merger
this.mergeValue = temp.oldMerger;
return temp.sum;
}
function mergeValue( key, val1, val2 )
{ // Default
// val1 + val2 should be the same as val2 + val1.
return (val1 + val2);
}
Example of Usage:
PHP Code:
function onCreated()
{
mod1 = TMap.newInstance({{"a",3}, {"b", 1}} );
mod2 = TMap.newInstance({{"a",2}, {"b", 1}, {"c", 1}} );
temp.merger = function( key, val1, val2 ) {
switch ( key )
{
case "a":
return val1 * val2;
default:
return val1 + val2;
}
};
mod3 = TMap.merge( mod1, mod2, temp.merger );
echo( mod3.toArray() ); // "a,6","b,2","c,1"
}