MCPcopy Create free account
hub / github.com/cryptii/cryptii / performTranslate

Method performTranslate

src/Encoder/SpellingAlphabet.js:162–196  ·  view source on GitHub ↗

* Performs encode or decode on given content. * @protected * @param {Chain} content * @param {boolean} isEncode True for encoding, false for decoding * @return {number[]|string|Uint8Array|Chain|Promise} Resulting content

(content, isEncode)

Source from the content-addressed store, hash-verified

160 * @return {number[]|string|Uint8Array|Chain|Promise} Resulting content
161 */
162 performTranslate (content, isEncode) {
163 // Retrieve content string and normalize its whitespaces
164 const string = StringUtil.normalizeWhitespaces(content.getString())
165
166 // Alphabet characters
167 const replacementMap = isEncode ? this._characterMap : this._wordMap
168 const searchValues =
169 Object.keys(replacementMap).sort((a, b) => b.length - a.length)
170
171 let index = 0
172 const resultValues = []
173
174 while (index < string.length) {
175 // Find next occurance in string
176 const searchValue = searchValues.find(value =>
177 string.substr(index, value.length).toLowerCase() === value.toLowerCase())
178
179 if (searchValue !== undefined) {
180 // Append char (in encode mode) or word (in decode mode) to result
181 resultValues.push(replacementMap[searchValue])
182 index += searchValue.length
183 } else {
184 const char = string.substr(index, 1)
185 // Omit whitespaces when decoding
186 if (isEncode || char !== ' ') {
187 // Append foreign character to result
188 resultValues.push(char)
189 }
190 index++
191 }
192 }
193
194 // String together result
195 return resultValues.join(isEncode ? ' ' : '')
196 }
197
198 /**
199 * Triggered when a setting field has changed.

Callers

nothing calls this directly

Calls 5

normalizeWhitespacesMethod · 0.80
getStringMethod · 0.80
toLowerCaseMethod · 0.80
substrMethod · 0.80
joinMethod · 0.80

Tested by

no test coverage detected