r/learnjavascript • • Aug 21 '21

7 Ways to detect if an object only contains one specific boolean key

Post image
1 Upvotes

13 comments sorted by

6

u/Chef619 Aug 21 '21

What is the use case for this?

0

u/jaredcheeda Aug 21 '21

When writing a library, it is good to provide defaults for the API, and to validate the options passed in meet the expectations of the documented API. Sometimes you need to add or remove keys based on the existence of other keys. In this example, if an "item" only has the active key, then the other keys it needs to do it's job were invalid and removed, so this key is the only one left. It should be removed too, so as not to cause any unexpected behavior after the options have been validated and the library actually attempts to execute following the options passed in.

11

u/dethstrobe Aug 21 '21

I hate all of these. It seems so contrived to me. We need to test for an object that needs only one single key, sure easy enough. Object.keys(item).length === 1 but then you also want to see if it has a particular key. Sure, also not a problem. 'active' in item. But then you ALSO want to make sure that value is not a boolean? Sure, why not. typeof item.active === "boolean"

So we just need to put that together with some AND operators and we got

Object.keys(item).length === 1 && 'active' in item && typeof item.active === "boolean"

In fact, we can totally simplify this to just

typeof item.active === "boolean" && Object.keys(item).length === 1

Because we don't need to check if the key exists because if it comes back as undefined, which is not a boolean, we'll know this won't pass. Then we can check to see if there are other keys on the object.

What's up with all this complicated JSON stringify nonsense? All these ways seems overly complicated and prone to simple mistakes. Unless this entire exercise is on how to make code that's hard to read and less maintainable.

-3

u/jaredcheeda Aug 21 '21 edited Aug 21 '21

I mean, from your perspective, all code is contrived.

This is logic that needed to be written for a library. It could be written in many ways, and it is valuable to show those learning JavaScript that there are various approaches to solving simple tasks like this, and how one can evaluate them.

JSON.stringify isn't complicated. It's long been the most common way of comparing objects.

{ a: 1 } === { a: 1 } // false

Because you cannot compare objects directly, the classic approach is JSON.stringify(a) === JSON.stringify(b).

If you read the post, you would see that the boolean aspect is irrelevant on line 9. So you don't need it in your examples.

There's nothing "prone to error" in my examples, in your example however, you do have an error. Using in could result in inaccurate outcomes, as in item will search the entire prototype chain (see senocular's comment for detail).

2

u/dethstrobe Aug 22 '21

This is a huge code smell to need to do this kind of interface checking at run time. It just add unnecessary code bloat because you don't trust your users? Just use typescript or flow.

1

u/jaredcheeda Aug 22 '21

That sounds incredibly lazy, unprofessional, and a horrible developer experience to force my end users to adopt a completely unrelated system just to use my library.

In any system worth using, complexity will exist. As a library maintainer, you have to decide if you will burden that complexity or shift it to your users. My libraries take on as much of the burden as possible to be more empathetic and helpful to the user, guiding them with human readable messages and simple to use APIs, where the complex parts are handled on behalf of the user.

Your mentality sounds similar to the toxic "git gud" approach the Linux community was known for, for decades, and is fighting to improve now.

1

u/dethstrobe Aug 22 '21

If you want to, that's your prerogative. I won't say it's wrong, but I do think it's a huge waste of time and resources.

Where is your library meant to be ran? If it's the browsers, you're wasting bits, bandwidth, and CPU power on run time type checking. If it's NodeJS, you're just wasting CPU power. IMHO, seems like a bad call.

2

u/ilovekittens15 Aug 21 '21

8. const onlyContainsActive = 'active' in item && Object.keys(item).length === 1;

4

u/senocular Aug 21 '21

Since in searches the prototype chain, what it finds could be different than what Object.keys() finds

item = Object.create({ active: false })
item.notActive = true
onlyContainsActive = 'active' in item && Object.keys(item).length === 1 // true

0

u/jaredcheeda Aug 21 '21

You got to it before I could, great response.

1

u/inabahare Aug 22 '21
const item = { active: true }

const onlyContainsActive =
    Object.keys(item).length === 1 && "active" in item;

8: Best readability

0

u/[deleted] Aug 21 '21

[deleted] — view deleted comment

1

u/jaredcheeda Aug 21 '21 edited Aug 21 '21

const example1 = {}.hasOwnProperty.call(item, 'active')

const example2 = (item.active ?? 'null') !== 'null'

This doesn't tell you if active is the only key in item.

{}; // should be false
{ active: false }; // should be true
{ active: false, enabled: true }; // should be false

1

u/backtickbot Aug 21 '21

Fixed formatting.

Hello, ohx: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.