Skip to content

Commit

Permalink
Avoid unnecesary prototype loop
Browse files Browse the repository at this point in the history
## 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.
  • Loading branch information
WebReflection authored May 25, 2020
1 parent 7bf8b06 commit 53c59b0
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions src/utils/isPlainObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@
* @returns True if the argument appears to be a plain object.
*/
export default function isPlainObject(obj: any): boolean {
if (typeof obj !== 'object' || obj === null) return false

let proto = obj
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto)
}

return Object.getPrototypeOf(obj) === proto
return (
typeof value === 'object' &&
value !== null &&
Object.getPrototypeOf(Object.getPrototypeOf(value) || {}) === null
)
}

0 comments on commit 53c59b0

Please sign in to comment.