diff --git a/src/backend/variables/builtin/array/array-slice.ts b/src/backend/variables/builtin/array/array-slice.ts new file mode 100644 index 000000000..16c0915b9 --- /dev/null +++ b/src/backend/variables/builtin/array/array-slice.ts @@ -0,0 +1,43 @@ +import { ReplaceVariable, Trigger } from "../../../../types/variables"; +import { OutputDataType, VariableCategory } from "../../../../shared/variable-constants"; + +const model : ReplaceVariable = { + definition: { + handle: "arraySlice", + description: "Returns a slice of an array", + usage: "arraySlice[array, start, end]", + categories: [VariableCategory.ADVANCED], + possibleDataOutput: [OutputDataType.TEXT] + }, + evaluator: ( + trigger: Trigger, + subject: string | unknown[], + start?: string | number, + end?: string | number + ) : unknown[] => { + if (typeof subject === 'string' || subject instanceof String) { + try { + subject = JSON.parse(`${subject}`); + } catch (ignore) { + return []; + } + } + if (!Array.isArray(subject)) { + return []; + } + + start = start ? Number(start) : 0; + if (Number.isNaN(start)) { + start = 0; + } + + end = end ? Number(end) : subject.length; + if (Number.isNaN(end)) { + end = subject.length; + } + + return [...subject].slice(start, end); + } +}; + +export default model; \ No newline at end of file diff --git a/src/backend/variables/builtin/array/index.ts b/src/backend/variables/builtin/array/index.ts index 6841c0838..9ae88a571 100644 --- a/src/backend/variables/builtin/array/index.ts +++ b/src/backend/variables/builtin/array/index.ts @@ -1,5 +1,5 @@ import arrayAdd from './array-add'; -import arrayElemenet from './array-element'; +import arrayElement from './array-element'; import arrayFilter from './array-filter'; import arrayFindIndex from './array-find-index'; import arrayFind from './array-find'; @@ -11,6 +11,7 @@ import arrayRandomItem from './array-random-item'; import arrayRemove from './array-remove'; import arrayReverse from './array-reverse'; import arrayShuffle from './array-shuffle'; +import arraySlice from './array-slice'; // Deprecated import rawArrayAdd from './raw-array-add'; @@ -27,7 +28,7 @@ import rawArrayShuffle from './raw-array-shuffle'; export default [ arrayAdd, - arrayElemenet, + arrayElement, arrayFilter, arrayFindIndex, arrayFind, @@ -39,6 +40,7 @@ export default [ arrayRemove, arrayReverse, arrayShuffle, + arraySlice, // Deprecated rawArrayAdd,