0

I have a set of numbers and an init number.

const mySet = new Set([1, 4, 5])
const initVal = 2

I want to find the smallest number greater than the initVal in mySet.

I could do something like...

let myArray = Array.from(mySet)
let smallestNumSoFar = Infinity
for (let num of myArray) {
    if (num > initVal && num < smallestNumSoFar) smallestNumSoFar = num; 
    }

But I was looking at this answer for python and it looks soo clean. Can anyone think of a nice one liner for javascript to do this? Something like Math.min of numbers>X in mySet

esafresa
  • 480
  • 7
  • 19
  • Do you need to do it efficiently, e.g. repeatedly on a large set? There are data structures that can implement a `Set` with *fast* O(log n) lookup of the smallest element greater than some value, not just short. (Alternatively, if your set never changes, you can get the same effect with a binary search.) – Ry- Nov 20 '22 at 07:57
  • 1
    "nice one liner" is not neededt. If you're going to reuse this (and thus need less code for every time you try) just write a function and call it. – VLAZ Nov 20 '22 at 07:58
  • Efficiency isn't so important, the set is <1000 numbers. And yes it's a function now, and I agree one-liners aren't important from a practical standpoint. But at the same time... I still appreciate a good one-liner. !needed !== !cool ;) – esafresa Nov 20 '22 at 08:14
  • 2
    [Off-topic]: Minor corrections to JS in your question: 1. `new Set` is a function, so it uses `()` not `{}`. 2. In JS, you should always declare your variables (mostly with `const`, or `let` if you explicitly ressign it) and 3. You want to use `for(_ of _)` not `for(_ in _)`. They're quite different and the `of` one is the way to go. – FZs Nov 20 '22 at 08:54

1 Answers1

3

Using the same efficiency of the Python example linked (O(n)), here's a simple one-liner.

const mySet = new Set([1, 4, 5]);
const initVal = 2

const min = Math.min(...[...mySet].filter((val) => val > initVal));

console.log(min);

You first need to convert the Set to an Array, then .filter it, and then use that with Math.min. Math.min expects multiple arguments, so the spread operator (...) is needed there. Similarly, to convert the Set to an Array (since Sets don't have a .filter method), it must be spread so that it's not an array with the 0th element being the set itself.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34