diff --git a/public/scripts/variables.js b/public/scripts/variables.js index c768c4f5e..343af9b16 100644 --- a/public/scripts/variables.js +++ b/public/scripts/variables.js @@ -836,6 +836,32 @@ function randValuesCallback(from, to, args) { return value; } +function sortArrayObjectCallback(args, value) { + let parsedValue; + if (typeof value == 'string') { + try { + parsedValue = JSON.parse(value); + } catch { + // return the original input if it was invalid + return value; + } + } else { + parsedValue = value + } + if (Array.isArray(parsedValue)) { + // always sort lists by value + parsedValue.sort() + } else if (typeof parsedValue == 'object') { + let keysort = args.keysort; + if (isFalseBoolean(keysort)) { + parsedValue = Object.keys(parsedValue).sort(function(a,b){return parsedValue[a]-parsedValue[b]}); + } else { + parsedValue = Object.keys(parsedValue).sort(); + } + } + return JSON.stringify(parsedValue); +} + /** * Declare a new variable in the current scope. * @param {NamedArguments} args Named arguments. @@ -2109,6 +2135,51 @@ export function registerVariableCommands() { `, })); + SlashCommandParser.addCommandObject(SlashCommand.fromProps({ + name: 'sort', + callback: sortArrayObjectCallback, + returns: 'the sorted list or dictionary keys', + namedArgumentList: [ + SlashCommandNamedArgument.fromProps({ name: 'keysort', + description: 'whether to sort by key or value; ignored for lists', + typeList: [ARGUMENT_TYPE.BOOLEAN], + enumList: ['true', 'false'], + defaultValue: 'true', + }), + ], + unnamedArgumentList: [ + SlashCommandArgument.fromProps({ + description: 'value', + typeList: [ARGUMENT_TYPE.STRING, ARGUMENT_TYPE.NUMBER, ARGUMENT_TYPE.LIST, ARGUMENT_TYPE.DICTIONARY], + isRequired: true, + forceEnum: false, + }), + ], + helpString: ` +
+ Sorts a list or dictionary in ascending order and passes the result down the pipe. + +
+
+ Examples: + +
+ `, + })); SlashCommandParser.addCommandObject(SlashCommand.fromProps({ name: 'rand', callback: (args, value) => String(randValuesCallback(Number(args.from ?? 0), Number(args.to ?? (value ? value : 1)), args)),