~eda-qa/dhlib/main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/* <license>
 * This file is part of the dis-Emi-A HaXe Library. Copyright © edA-qa mort-ora-y
 * For full copyright and license information please refer to doc/license.txt.
 * </license> 
 */

/**
 * A collection of functions for working with Dynamic objects
 */
class DynamicUtil
{
	/**
	 * Merge two dynamic objects into one, combining all fields
	 *
	 * @param high [in] fields in this item take precedence over low if duplicates
	 * @param low [in] item to merge, if duplicate fields with high, the ones in high take precedence
	 * @return out [in] a new Dynamic with the combined fields
	 */
	static public function merge( high : Dynamic, low : Dynamic ) : Dynamic
	{
		var out = {};
		for( field in Reflect.fields( low ) )
			Reflect.setField( out, field, Reflect.field( low, field ) );
		for( field in Reflect.fields( high ) )
			Reflect.setField( out, field, Reflect.field( high, field ) );
		return out;
	}
	
	/**
	 * Obtains a value from the Dynamic item, using a default if nothing is defined.
	 *
	 * @param opts [in] which dynamic item to look in. This may be null, in which
	 *		case the default will be returned
	 *	@param field [in] which field to look for
	 * @param def [in] will be returned if the field could not be found
	 * @return [out] either the found field or the default
	 *
	 * NOTE: if the field is found and is null then null will be returned.
	 */
	static public function defGet<T>( opts : Dynamic, field : String, def : T ) : T
	{
		if( opts == null )
			return def;
			
		if( !Reflect.hasField( opts, field ) )
			return def;
			
		return Reflect.field( opts, field );
	}
	
	/**
	 * Compares two objects based on their real types.
	 */
	static public function areEqual( a : Dynamic, b : Dynamic ) : Bool
	{
		//object compare?
		if( a == b )
			return true;
			
		//Numeric, also covers Int
		if( Std.is( a, Float ) )
		{
			if( !Std.is( b, Float ) )
				return false;
				
			return cast( a, Float ) == cast( b, Float );
		}
		
		//string
		if( Std.is( a, String ) )
		{
			if( !Std.is( b, String ) )
				return false;
				
			return cast( a, String ) == cast( b, String );
		}
		
		//generic convert error
		try 
		{
			return a.compare( b ) == 0;
		}
		catch( ex : TypesNotComparableError )
		{
			return false;
		}
		catch( ex : Dynamic )
		{
			//TODO: trap native exceptions and check only for Type errors, if not
			//a type error then propagate the error...
			return false;
			//trace( ex );
		}
		
		return false;
	}
}