Debian Codegraph @

Nasal/std/hash.nas

raw
1 # SPDX-License-Identifier: GPL-2.0-or-later
2 #
3 # NOTE! This copyright does *not* cover user models that use these Nasal
4 # services by normal function calls - this is merely considered normal use
5 # of the code, and does *not* fall under the heading of "derived work."
6 #-------------------------------------------------------------------------------
7 # hash.nas - simple hash class for development, allows to add callback on write
8 # author: Henning Stahlke
9 # created: 07/2020
10 #-------------------------------------------------------------------------------
11
12 #load only once (via /Nasal/std.nas) not via C++ module loader
13 if (ishash(globals["std"]) and ishash(std["Hash"]))
14 return;
15
16 Hash = {
17 new: func(hash=nil, name="") {
18 var obj = {
19 parents: [me],
20 name: name,
21 _h: {},
22 _callback: func,
23 };
24 if (ishash(hash))
25 obj._h = hash;
26 return obj;
27 },
28
29 set: func (key, value) {
30 me._h[key] = value;
31 me._callback(key, value);
32 return me;
33 },
34
35 get: func (key) {
36 return me._h[key];
37 },
38
39 clear: func() {
40 me._h = {};
41 return me;
42 },
43
44 contains: func(key) {
45 return contains(me._h, key);
46 },
47
48 getName: func () {
49 return me.name;
50 },
51
52 getKeys: func () {
53 return keys(me._h);
54 },
55
56 # export keys to props p/<keys>
57 # p: root property path or props.Node object
58 keys2props: func (p) {
59 if (!isa(p, props.Node)) {
60 p = props.getNode(p, 1);
61 }
62 foreach (var key; keys(me._h)) {
63 p.getNode(key, 1);
64 }
65 return me;
66 },
67
68 # export hash to props p/<key>=<value>
69 # p: root property path or props.Node object
70 hash2props: func (p) {
71 if (!isa(p, props.Node)) {
72 p = props.getNode(p, 1);
73 }
74 p.setValues(me._h);
75 return me;
76 },
77
78 # callback for set()
79 addCallback: func (f) {
80 if (isfunc(f)) {
81 me._callback = f;
82 return me;
83 }
84 return nil;
85 },
86 };