Here’s a mathematical approach which should give you the same results as the chained conditions approach:
degree = $context.response.data.hourly.0.wind_deg
directions = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
index = round((degree % 360) / 22.5)
directions[index % 16]
If you’re curious about the details on how this works or what the logic is…
How it works (tap to expand)
The way it works, line-by-line, is:
- Alias
wind_deg
from the response to a degree
local variable
- Just makes it easier to reference the value without typing the long name
- Define all the cardinal directions we are interested in (16 of them)
- Get an index based on which of the 16 positions it falls into
degree % 360
is a safety measure to make sure the value is always 0-360.
- For example, if it was 361, this would ‘wrap’ it back to 1
- 22.5 represents the range for each direction (360 / 16 positions = 22.5)
- So we divide our coerced degrees by 22.5 to find the index
(eg. which of the ‘directions’ values to grab)
- Get the cardinal direction based on the index
- Again, using the modulus operator to coerce to a valid 0 based index
Simple Direction
Using that same logic, you could simplify things to just the cardinal and intercardinal directions if you wanted (eg. drop the NNE, ENE, etc):
degree = $context.response.data.hourly.0.wind_deg
directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
index = round((degree % 360) / 45)
directions[index % 8]
As you can see, it’s a simple update trimming down the list of directions and adjusting the numbers accordingly. (eg. we only have 8 directions now, so its 45 degrees each)