forked from fponticelli/thx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashes.hx
126 lines (112 loc) · 2.58 KB
/
Hashes.hx
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* ...
* @author Franco Ponticelli
*/
import DynamicsT;
import thx.collection.Set;
class Hashes
{
public static function entries<T>(h : Hash<T> ) : Array<{ key : String, value : T }>
{
var arr = [];
for (key in h.keys())
arr.push({ key : key, value : h.get(key) });
return arr;
}
public static function toDynamic<T>(hash : Hash<T>) : Dynamic<T>
{
var o : Dynamic<T> = { };
for (key in hash.keys())
Reflect.setField(o, key, hash.get(key));
return o;
}
public static function importObject<T>(hash : Hash<T>, ob : Dynamic<T>) : Hash<T>
{
return DynamicsT.copyToHash(ob, hash);
}
public static function copyTo<T>(from : Hash<T>, to : Hash<T>)
{
for (k in from.keys())
to.set(k, from.get(k));
return to;
}
public static function clone<T>(src : Hash<T>)
{
var h = new Hash();
Hashes.copyTo(src, h);
return h;
}
public static inline function arrayOfKeys(hash : Hash<Dynamic>)
{
return Iterators.array(hash.keys());
}
public static function setOfKeys(hash : Hash<Dynamic>) : Set<String>
{
var set = new Set();
for(k in hash.keys())
set.add(k);
return set;
}
public static inline function empty(hash : Hash<Dynamic>) return count(hash) == 0
public static function count(hash : Hash<Dynamic>)
{
#if neko
return untyped __dollar__hsize(hash.h);
#elseif php
return untyped __call__('count', hash.h);
#else
var i = 0;
for (_ in hash)
i++;
return i;
#end
}
public static function mergef<T>(hash : Hash<T> , new_hash : Hash<T> , f:String->T->T->T)
{
for (k in new_hash.keys()){
var new_val = new_hash.get(k);
if (hash.exists(k)){
var old_val = hash.get(k);
hash.set(k, f(k, old_val, new_val));
} else{
hash.set(k,new_val);
}
}
}
public static function merge<T>(hash : Hash<T> , new_hash : Hash<T>)
{
mergef(hash,new_hash, function(key, old_v,new_v) return new_v);
}
public static function clear(hash : Hash<Dynamic>)
{
#if cpp
var _hash : { private var __Internal : Dynamic; } = hash;
_hash.__Internal = {};
#else
var _hash : FriendHash = hash;
#if flash9
_hash.h = new flash.utils.Dictionary();
#elseif flash
_hash.h = untyped __new__(_global["Object"]);
#elseif neko
_hash.h = untyped __dollar__hnew(0);
#elseif js
untyped {
_hash.h = __js__("{}");
if( _hash.h.__proto__ != null ) {
_hash.h.__proto__ = null;
__js__("delete")(_hash.h.__proto__);
}
}
#elseif php
_hash.h = untyped __call__('array');
#end
#end
}
}
typedef FriendHash = {
private var h :
#if flash9 flash.utils.Dictionary
#elseif php ArrayAccess<Dynamic>
#else Dynamic #end;
}