From e806f71888992f56ba0cec5b1861491b1b85e535 Mon Sep 17 00:00:00 2001 From: David Byrne Date: Tue, 12 May 2020 19:13:39 -0600 Subject: [PATCH] Added Length operation Added "Length" operation that returns the length of the input string. It can return in bytes, characters (i.e., Unicode), or JavaScript's UTF-16 units. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) --- src/core/config/Categories.json | 1 + src/core/operations/Length.mjs | 61 +++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/core/operations/Length.mjs diff --git a/src/core/config/Categories.json b/src/core/config/Categories.json index 77e3d319..4f2fe866 100755 --- a/src/core/config/Categories.json +++ b/src/core/config/Categories.json @@ -225,6 +225,7 @@ "Filter", "Head", "Tail", + "Length", "Count occurrences", "Expand alphabet range", "Drop bytes", diff --git a/src/core/operations/Length.mjs b/src/core/operations/Length.mjs new file mode 100644 index 00000000..add31596 --- /dev/null +++ b/src/core/operations/Length.mjs @@ -0,0 +1,61 @@ +/** + * @author David Byrne [davidribyrne@users.noreply.github.com] + * @copyright David Byrne 2020 + * @license Apache-2.0 + */ + +import Operation from "../Operation.mjs"; + +const BYTES = "Bytes"; +const CHARS = "Characters"; +const UTF = "UTF-16 units"; + +/** + * Length operation + */ +class Length extends Operation { + + + /** + * Length constructor + */ + constructor() { + super(); + + this.name = "Length"; + this.module = "Default"; + this.description = "Returns the input length.

" + + "Bytes - Number of bytes (Unicode characters may have up to 4 bytes)
" + + "Characters - Number of Unicode characters
" + + "UTF-16 units - See information URL for details "; + this.infoURL = "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length"; + this.inputType = "string"; + this.outputType = "number"; + this.args = [ + { + name: "First arg", + type: "option", + value: [BYTES, CHARS, UTF] + } + ]; + } + + /** + * @param {string} input + * @param {Object[]} args + * @returns {number} + */ + run(input, args) { + switch (args[0]) { + case BYTES: + return new Blob([input]).size; + case CHARS: + return Array.from(input).length; + case UTF: + return input.length; + } + } + +} + +export default Length;