Skip to content

Commit

Permalink
Add support for TypedArrays for replace() method
Browse files Browse the repository at this point in the history
  • Loading branch information
lahmatiy committed May 18, 2024
1 parent 90f70e1 commit c7afead
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/methods.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,14 +231,21 @@ export default Object.freeze({
return String(current).split(pattern);
},
replace(current, pattern, replacement) {
if (Array.isArray(current)) {
if (isArray(current)) {
const patternFn = typeof pattern === 'function' ? pattern : Object.is.bind(null, pattern);
const result = [...current];

return current.map(
typeof replacement === 'function'
? current => patternFn(current) ? replacement(current) : current
: current => patternFn(current) ? replacement : current
);
for (let i = 0; i < result.length; i++) {
const value = result[i];

if (patternFn(value)) {
result[i] = typeof replacement === 'function'
? replacement(value)
: replacement;
}
}

return result;
}

if (isRegExp(pattern) && !pattern.flags.includes('g')) {
Expand Down
7 changes: 7 additions & 0 deletions test/methods/replace.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ describe('replace()', () => {
});
});

it('should work with TypedArray', () => {
assert.deepEqual(
query('replace(=>$%2,=>"odd")')(new Uint8Array([3, 2, 1, 4])),
['odd', 2, 'odd', 4]
);
});

describe('any other values', () => {
it('non-string value', () => {
assert.strictEqual(
Expand Down

0 comments on commit c7afead

Please sign in to comment.