Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly check if a Set is empty

I've come with a question regarding the best way to check if a Javascript Set is empty. According with documentation, there is no a straightforward method to check or get Set items.

I think it happens same with Map.

I've come up with some ideas (Node.js), but I'm not quite sure what's better.

const assert = require('assert');

const emptySet = new Set()
assert.strictEqual(![...emptySet].length, true)
assert.strictEqual(emptySet.values().next().value === undefined, true)
assert.strictEqual(emptySet.entries().next().value === undefined, true)

const twoItemsSet = new Set([ 'foo', 'bar' ])
assert.strictEqual(![...twoItemsSet].length, false)
assert.strictEqual(twoItemsSet.values().next().value === undefined, false)
assert.strictEqual(twoItemsSet.entries().next().value === undefined, false)
like image 708
Antonio B R Avatar asked May 05 '17 15:05

Antonio B R


People also ask

How do you check if a set is empty?

Set. isEmpty() method is used to check if a Set is empty or not. It returns True if the Set is empty otherwise it returns False.

Is empty set false Python?

In python, an empty set always evaluates to false. So when we passed an empty set to the if condition it'll be evaluated to false. But the not operator reverses the false value to true value.


1 Answers

emptySet.size == 0

MDN Documentation

like image 108
Kyle Becker Avatar answered Oct 05 '22 09:10

Kyle Becker