EN
JavaScript - add value to Set and return true on success or false on fail
3
points
In this article, we would like to show you how to add value to Set and return true on success or false on fail in JavaScript.
Quick solution:
const set = new Set();
if (set.size !== (set.add('Some value ...'), set.size)) {
console.log('Some value added!');
}
Practical examples
1. Using size accessor
In this example, we check the set size before and after adding a value to it. If the sizes are the same, it means the element hasn't been added and the function returns false, otherwise returns true.
// ONLINE-RUNNER:browser;
const addValue = (set, value) => set.size !== (set.add(value), set.size);
// Usage example:
const set = new Set();
console.log(addValue(set, 'a')); // true
console.log(addValue(set, 'a')); // false
console.log(addValue(set, 'b')); // true
console.log(addValue(set, 'c')); // true
2. Using has() method
In this example, we use has() method to check whether an element with the specified value exists in a Set object. If the value exist, it means the element can't be added and the function returns false, otherwise returns true.
// ONLINE-RUNNER:browser;
const addValue = (set, value) => set.has(value) ? false : (set.add(value), true);
// or: const addValue = (set, value) => !set.has(value) && (set.add(value), true);
// Usage example:
const set = new Set();
console.log(addValue(set, 'a')); // false
console.log(addValue(set, 'a')); // true
console.log(addValue(set, 'b')); // false
console.log(addValue(set, 'c')); // false