* Replace a substring in a string * @param {string} str string to be replaced * @param {Index} index An index or list of indices (character positions) * @param {string} replacement Replacement string * @param {string} [defaultValue] Default value to be used when resizing
(str, index, replacement, defaultValue)
| 183 | * @private |
| 184 | */ |
| 185 | function _setSubstring (str, index, replacement, defaultValue) { |
| 186 | if (!index || index.isIndex !== true) { |
| 187 | // TODO: better error message |
| 188 | throw new TypeError('Index expected') |
| 189 | } |
| 190 | if (isEmptyIndex(index)) { return str } |
| 191 | validateIndexSourceSize(Array.from(str), index) |
| 192 | if (index.size().length !== 1) { |
| 193 | throw new DimensionError(index.size().length, 1) |
| 194 | } |
| 195 | if (defaultValue !== undefined) { |
| 196 | if (typeof defaultValue !== 'string' || defaultValue.length !== 1) { |
| 197 | throw new TypeError('Single character expected as defaultValue') |
| 198 | } |
| 199 | } else { |
| 200 | defaultValue = ' ' |
| 201 | } |
| 202 | |
| 203 | const range = index.dimension(0) |
| 204 | const len = Number.isInteger(range) ? 1 : range.size()[0] |
| 205 | |
| 206 | if (len !== replacement.length) { |
| 207 | throw new DimensionError(range.size()[0], replacement.length) |
| 208 | } |
| 209 | |
| 210 | // validate whether the range is out of range |
| 211 | const strLen = str.length |
| 212 | validateIndex(index.min()[0]) |
| 213 | validateIndex(index.max()[0]) |
| 214 | |
| 215 | // copy the string into an array with characters |
| 216 | const chars = [] |
| 217 | for (let i = 0; i < strLen; i++) { |
| 218 | chars[i] = str.charAt(i) |
| 219 | } |
| 220 | |
| 221 | function callback (v, i) { |
| 222 | chars[v] = replacement.charAt(i[0]) |
| 223 | } |
| 224 | |
| 225 | if (Number.isInteger(range)) { |
| 226 | callback(range, [0]) |
| 227 | } else { |
| 228 | range.forEach(callback) |
| 229 | } |
| 230 | |
| 231 | // initialize undefined characters with a space |
| 232 | if (chars.length > strLen) { |
| 233 | for (let i = strLen - 1, len = chars.length; i < len; i++) { |
| 234 | if (!chars[i]) { |
| 235 | chars[i] = defaultValue |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | return chars.join('') |
| 241 | } |
| 242 |
nothing calls this directly
no test coverage detected
searching dependent graphs…