SKB
Neues Mitglied
Hallo,
ich habe eine Javascript Function, welche aus einem Object (over) Zahlen oder Strings als Keys vergleicht und das beste "Match" herauszieht.
Dieses Match enthält meistens 1 oder mehrere Properties, die sowohl String, Zahlen, aber auch Strings als Functions enthalten können.
Wenn ich die Funktion einmal Aufrufe, funktioniert sie problemlos - sobald ich sie aber ein 2. Mal aufrufe, werden einfach nur die Werte vom vorherigen Aufruf übernommen. Könnte mir jemand auf den Sprung helfen? Ich habe irgendwie das Gefühl, das es etwas mit den "new Function" auf sich hat.
Vielen Dank!
	
	
	
		
				
			ich habe eine Javascript Function, welche aus einem Object (over) Zahlen oder Strings als Keys vergleicht und das beste "Match" herauszieht.
Dieses Match enthält meistens 1 oder mehrere Properties, die sowohl String, Zahlen, aber auch Strings als Functions enthalten können.
Wenn ich die Funktion einmal Aufrufe, funktioniert sie problemlos - sobald ich sie aber ein 2. Mal aufrufe, werden einfach nur die Werte vom vorherigen Aufruf übernommen. Könnte mir jemand auf den Sprung helfen? Ich habe irgendwie das Gefühl, das es etwas mit den "new Function" auf sich hat.
Vielen Dank!
		Javascript:
	
	const over = {
            ">=22": {
                "fill": "#FF0000",
                "value": "val => Number(Number(5)+Number(5))+Number(10)+val",
                "unit": "val => val >= 1000 ? 'kW' : 'W'"
            },
            "default": {
                "fill": "#FFFFFF",
                "value": "val => parseFloat(val/1000).toFixed(2)",
                "unit": "val => Math.abs(val) > 1000 ? 'kW' : 'W'"
            }
        };
        /**
             *
             * @param {string} id
             * @param {number} condValue
             * @param {object} object
             * @returns {object} result
             */
        // Testing for Override
        function getOverrides(id, condValue, object) {
            let result = {};
            const workObj = typeof (object) === 'string' ? JSON.parse(object) : object;
            if (workObj.hasOwnProperty(condValue)) {
                // Check, if Property exists - if yes, directly return it, because thats the best match
                result = workObj[condValue];
            } else {
                // Property not found. We need to check the values!
                const operators = new RegExp('[=><!]');
                Object.keys(workObj)
                    .sort(
                        (a, b) => a.toLowerCase().localeCompare(b.toLowerCase(), undefined, { numeric: true, sensitivity: 'base' }))
                    .forEach((item) => {
                        if (operators.test(item)) {
                            // Now, we need to check, if condValue is a number
                            if (!isNaN(condValue)) {
                                // Operator found - check for condition
                                try {
                                    const func = Function(`return ${condValue}${item}`)();
                                    if (func) {
                                        result = workObj[item];
                                    }
                                }
                                catch (func) {
                                    result = workObj[item];
                                    result.error = {
                                        status: false,
                                        error: func.toString(),
                                        func: condValue
                                    }
                                }
                            }
                        }
                    });
            }
            if (Object.keys(result).length == 0) {
                // Check, if we have a fallback for it
                if (workObj.hasOwnProperty('default')) {
                    result = workObj['default'];
                }
            }
            // Process the result values, if available
            if (Object.keys(result).length > 0) {
                // Value
                if (result.hasOwnProperty('value')) {
                    try {
                        const valueFunc = new Function("return " + result.value)();
                        result.value = valueFunc(condValue);
                    }
                    catch (valueFunc) {
                        result.value = result.value;
                        result.error = {
                            status: false,
                            error: valueFunc.toString(),
                            function: result.value
                        };
                    }
                }
                // Unit
                if (result.hasOwnProperty('unit')) {
                    try {
                        const unitFunc = new Function(`return ${result.unit}`)();
                        result.unit = unitFunc(condValue);
                    }
                    catch (unitFunc) {
                        result.unit = result.unit;
                        result.error = {
                            status: false,
                            error: unitFunc.toString(),
                            function: result.unit
                        };
                    }
                }
            }
            return result;
        }
        console.log(getOverrides(1, 50, over));
        console.log(getOverrides(2, 1000, over)); 
	