Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
renovate
Manage
Activity
Members
Code
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Deploy
Releases
Model registry
Analyze
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
GitHub Mirror
Renovate Bot
renovate
Commits
0d6a8882
Unverified
Commit
0d6a8882
authored
1 year ago
by
Sergei Zharinov
Committed by
GitHub
1 year ago
Browse files
Options
Downloads
Patches
Plain Diff
feat: Add `filterMap` utility for fast array transforms (#23252)
parent
54dcdf01
Branches
Branches containing commit
Tags
Tags containing commit
No related merge requests found
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
lib/util/filter-map.spec.ts
+17
-0
17 additions, 0 deletions
lib/util/filter-map.spec.ts
lib/util/filter-map.ts
+26
-0
26 additions, 0 deletions
lib/util/filter-map.ts
with
43 additions
and
0 deletions
lib/util/filter-map.spec.ts
0 → 100644
+
17
−
0
View file @
0d6a8882
import
{
filterMap
}
from
'
./filter-map
'
;
describe
(
'
util/filter-map
'
,
()
=>
{
it
(
'
should return an empty array when given an empty array
'
,
()
=>
{
const
input
:
unknown
[]
=
[];
const
output
=
filterMap
(
input
,
()
=>
42
);
expect
(
output
).
toBe
(
input
);
expect
(
output
).
toBeEmpty
();
});
it
(
'
should return an array with only the mapped values that pass the filter
'
,
()
=>
{
const
input
=
[
0
,
1
,
2
,
3
,
4
];
const
output
=
filterMap
(
input
,
(
n
)
=>
n
*
n
);
expect
(
output
).
toBe
(
input
);
expect
(
output
).
toEqual
([
1
,
4
,
9
,
16
]);
});
});
This diff is collapsed.
Click to expand it.
lib/util/filter-map.ts
0 → 100644
+
26
−
0
View file @
0d6a8882
import
is
from
'
@sindresorhus/is
'
;
type
Falsy
=
false
|
''
|
0
|
0
n
|
null
|
undefined
;
/**
* Filter and map an array *in place* with single iteration.
*/
export
function
filterMap
<
T
,
U
>
(
array
:
T
[],
fn
:
(
item
:
T
)
=>
Falsy
|
U
):
U
[]
{
const
length
=
array
.
length
;
let
newIdx
=
0
;
for
(
let
oldIdx
=
0
;
oldIdx
<
length
;
oldIdx
+=
1
)
{
const
item
=
array
[
oldIdx
];
const
res
=
fn
(
item
);
if
(
is
.
truthy
(
res
))
{
array
[
newIdx
]
=
res
as
never
;
newIdx
+=
1
;
}
}
const
deletedCount
=
length
-
newIdx
;
if
(
deletedCount
)
{
array
.
length
=
length
-
deletedCount
;
}
return
array
as
never
;
}
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment