This is an old number crunching problem. Think about it, the Absolute difference between any two compass directions can never exceed 180° (-180° to +180°). This can be solved with a one-liner with two operands,
-Diff *(abs(diff)<=180)-(360+(abs(diff)>180))
(Where "Yes" from the logical operand yields -1, and "No" yields 0)
Done in great haste, check the signs, but there's a start point.
Regards,
Old Smokey