Skip to content

Commit 02dff7f

Browse files
committed
Avoid unnecesary prototype loop
## Background People at redux-toolkit copy/pasted this utility in there, and [they are not welcoming a PR](reduxjs/redux-toolkit#581) because of that, but the `while` loop in here is completely unnecessary, as the comparison is made on the first `proto` only. ## Improvements * _O(1)_ instead of _O(n)_ * safe fallback for `Object.create(null)` cases * fast lane for `new Class()` derived objects * better performance * smaller code size As this change has zero downsides, unless I am missing some explicit reason to `while` loop instead of never using `getPrototypeOf` more than twice, I hope it'll get in, so that others might copy and paste this new version. Best Regards.
1 parent 7bf8b06 commit 02dff7f

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

src/utils/isPlainObject.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,9 @@
33
* @returns True if the argument appears to be a plain object.
44
*/
55
export default function isPlainObject(obj: any): boolean {
6-
if (typeof obj !== 'object' || obj === null) return false
7-
8-
let proto = obj
9-
while (Object.getPrototypeOf(proto) !== null) {
10-
proto = Object.getPrototypeOf(proto)
11-
}
12-
13-
return Object.getPrototypeOf(obj) === proto
6+
return (
7+
typeof obj === 'object' &&
8+
obj !== null &&
9+
Object.getPrototypeOf(Object.getPrototypeOf(obj) || {}) === null
10+
)
1411
}

0 commit comments

Comments
 (0)