Sheet formula

If you want to replicate the logic in the Sheet, you can convert the if-then-else logic to an arrayformula.