Library globals

Source std . hash.nas

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
# SPDX-License-Identifier: GPL-2.0-or-later
#
# NOTE! This copyright does *not* cover user models that use these Nasal
# services by normal function calls - this is merely considered normal use
# of the code, and does *not* fall under the heading of "derived work."
#-------------------------------------------------------------------------------
# hash.nas - simple hash class for development, allows to add callback on write
# author:       Henning Stahlke
# created:      07/2020
#-------------------------------------------------------------------------------

#load only once (via /Nasal/std.nas) not via C++ module loader
if (ishash(globals["std"]) and ishash(std["Hash"])) 
    return;

Hash = {
    new: func(hash=nil, name="") {
        var obj = {
            parents: [me],
            name: name,
            _h: {},
            _callback: func,
        };
        if (ishash(hash)) 
            obj._h = hash;
        return obj;
    },
   
    set: func (key, value) {
        me._h[key] = value;
        me._callback(key, value);
        return me;
    },
    
    get: func (key) {
        return me._h[key];
    },

    clear: func() {
        me._h = {};
        return me;
    },
    
    contains: func(key) {
        return contains(me._h, key);
    },
    
    getName: func () {
        return me.name;
    },
    
    getKeys: func () {
        return keys(me._h);
    },
    
    # export keys to props p/<keys>
    # p:    root property path or props.Node object
    keys2props: func (p) {
        if (!isa(p, props.Node)) {
            p = props.getNode(p, 1);
        }
        foreach (var key; keys(me._h)) {
            p.getNode(key, 1);
        }
        return me;
    },
    
    # export hash to props p/<key>=<value>
    # p:    root property path or props.Node object
    hash2props: func (p) {
        if (!isa(p, props.Node)) {
            p = props.getNode(p, 1);
        }
        p.setValues(me._h);
        return me;
    },
    
    # callback for set()
    addCallback: func (f) {
        if (isfunc(f)) {
            me._callback = f;
            return me;
        }
        return nil;
    },
};