A lightweight function designed to generate number sequences based on the sequence type.
Supported Sequence Types
arithmetic
- Arithmetic Sequence
geometric
- Geometric Sequence
fibonacci
- Fibonacci Sequence
harmonic
- Harmonic Sequence
Usage
$sequence[start;terms;constant;sep?]
Parameters
@param {String} type - The type of sequence to be generated. Value is either 'arithmetic', 'geometric', 'fibonacci', or 'harmonic'
start
- The first term of the sequence, must be integer. (Required)
terms
- The number of terms to be generated, must be integer. (Required)
constant
- The common difference or common ratio, this is not used when the sequence type is 'fibonacci'. (Required)
sep
- The separator for each term, default separator is a comma. (Optional)
Source Code
/**
* @param {String} type - The type of sequence to be generated. Value is either 'arithmetic', 'geometric', 'fibonacci', or 'harmonic'
* @param {Number} start - The first term of the sequence, must be integer.
* @param {Number} terms - The number of terms to be generated, must be integer.
* @param {Number} constant - The common difference or common ratio, this is not used when the sequence type is 'fibonacci'.
* @param {String} sep - The separator for each terms, default separator is comma.
*/
module.exports = {
name: "$sequence",
type: "djs",
code: async function (d) {
let data = d.util.aoiFunc(d);
let [type, start, terms, constant, sep = ", "] = data.inside.splits; // Extract parameters
const isValidType = ["arithmetic", "geometric", "fibonacci", "harmonic"].includes(type); // Validate sequence type
const isValidParams = [start, terms, constant].every(param => Number.isInteger(parseInt(param, 10))); // Validate the parameters if integers
if (!isValidType || !isValidParams) { // Checks if all parameters are valid
d.aoiError.consoleError("Error", "Invalid values provided in parameters"); // Logs the error in the console
return d.aoiError.fnError(d, "custom", {}, "Invalid Parameters"); // Sends an AoiError message
}
const sequence = []; // Initializes the sequence array
start = parseInt(start, 10); // Parse the first term as integer
constant = parseInt(constant, 10); // Parse the common ratio or difference as integer
// Generate sequences based on the specified type
for (let i = 0; i < terms; i++) {
switch (type) {
case "arithmetic":
// Arithmetic sequence formula
sequence.push(start + i * constant);
break;
case "geometric":
// Geometric sequence formula
sequence.push(start * Math.pow(constant, i));
break;
case "fibonacci":
// Fibonacci sequence formula
sequence.push(start);
[start, constant] = [constant, start + constant];
break;
case "harmonic":
// Harmonic sequence formula
sequence.push(1 / (start + i * constant));
break;
}
}
data.result = sequence.join(sep); // Joins all terms with the separator and sets the sequence array as the result
return { code: d.util.setCode(data) };
}
};