CyberChef/src/core/Ingredient.js

93 lines
2 KiB
JavaScript
Raw Normal View History

import Utils from "./Utils.js";
2016-11-28 10:42:58 +00:00
/**
* The arguments to operations.
*
* @author n1474335 [n1474335@gmail.com]
* @copyright Crown Copyright 2016
* @license Apache-2.0
*
* @class
* @param {Object} ingredientConfig
2016-11-28 10:42:58 +00:00
*/
2017-04-13 17:08:50 +00:00
const Ingredient = function(ingredientConfig) {
2016-11-28 10:42:58 +00:00
this.name = "";
this.type = "";
this.value = null;
2017-02-09 15:09:33 +00:00
if (ingredientConfig) {
this._parseConfig(ingredientConfig);
2016-11-28 10:42:58 +00:00
}
};
/**
* Reads and parses the given config.
*
* @private
* @param {Object} ingredientConfig
2016-11-28 10:42:58 +00:00
*/
Ingredient.prototype._parseConfig = function(ingredientConfig) {
this.name = ingredientConfig.name;
this.type = ingredientConfig.type;
2016-11-28 10:42:58 +00:00
};
/**
* Returns the value of the Ingredient as it should be displayed in a recipe config.
*
* @returns {*}
*/
Ingredient.prototype.getConfig = function() {
2016-11-28 10:42:58 +00:00
return this.value;
};
/**
* Sets the value of the Ingredient.
*
* @param {*} value
*/
Ingredient.prototype.setValue = function(value) {
2016-11-28 10:42:58 +00:00
this.value = Ingredient.prepare(value, this.type);
};
/**
* Most values will be strings when they are entered. This function converts them to the correct
* type.
*
* @static
* @param {*} data
* @param {string} type - The name of the data type.
*/
Ingredient.prepare = function(data, type) {
2017-04-13 17:31:26 +00:00
let number;
2017-05-02 21:53:57 +00:00
2016-11-28 10:42:58 +00:00
switch (type) {
case "binaryString":
case "binaryShortString":
case "editableOption":
return Utils.parseEscapedChars(data);
case "byteArray":
2016-11-28 10:42:58 +00:00
if (typeof data == "string") {
2016-12-14 16:39:17 +00:00
data = data.replace(/\s+/g, "");
return Utils.fromHex(data);
2016-11-28 10:42:58 +00:00
} else {
return data;
}
case "number":
2017-04-13 17:31:26 +00:00
number = parseFloat(data);
2016-11-28 10:42:58 +00:00
if (isNaN(number)) {
2017-04-13 17:08:50 +00:00
const sample = Utils.truncate(data.toString(), 10);
2016-11-28 10:42:58 +00:00
throw "Invalid ingredient value. Not a number: " + sample;
}
return number;
default:
return data;
}
};
export default Ingredient;