fix(compat/forEach): remove redundant array check in key resolution#1869
fix(compat/forEach): remove redundant array check in key resolution#1869Antoliny0919 wants to merge 1 commit into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
| if (!collection) { | ||
| return collection; | ||
| } |
There was a problem hiding this comment.
It looks like this is only intended to handle null and undefined.
With the current implementation, it would also treat other falsy values as empty, which seems broader than intended.
Would it make sense to explicitly handle only null and undefined instead?
index f0f6fb48..8aa3bbcf 100644
--- a/src/compat/array/forEach.ts
+++ b/src/compat/array/forEach.ts
@@ -144,7 +144,7 @@ export function forEach<T>(
collection: ArrayLike<T> | Record<any, any> | string | null | undefined,
callback: (item: any, index: any, arr: any) => unknown = identity
): ArrayLike<T> | Record<any, any> | string | null | undefined {
- if (!collection) {
+ if (collection == null) {
return collection;
}One thing I'm curious about: do you have a preference between using a raw collection == null check and using isNil for this kind of logic?
Personally, I think using isNil is perfectly reasonable. In fact, I'd be happy to standardize on isNil for null/undefined checks going forward.
index f0f6fb48..a1a93f68 100644
--- a/src/compat/array/forEach.ts
+++ b/src/compat/array/forEach.ts
@@ -1,5 +1,6 @@
import { identity } from '../../function/identity.ts';
import { range } from '../../math/range.ts';
+import { isNil } from '../../predicate/isNil.ts';
import { ArrayIterator } from '../_internal/ArrayIterator.ts';
import { ListIterator } from '../_internal/ListIterator.ts';
import { ObjectIterator } from '../_internal/ObjectIterator.ts';
@@ -144,7 +145,7 @@ export function forEach<T>(
collection: ArrayLike<T> | Record<any, any> | string | null | undefined,
callback: (item: any, index: any, arr: any) => unknown = identity
): ArrayLike<T> | Record<any, any> | string | null | undefined {
- if (!collection) {
+ if (isNil(collection)) {
return collection;
}Using isNil does introduce a dependency on that utility, but I think there are both pros and cons to that. Since isNil is such a fundamental utility that's unlikely to change, I also feel it makes the intent more explicit.
Since arrays and array like objects are handled the same way, I think
isArrayLikealone should be sufficient.