decode
decode(subject, v1, r1, v2, r2, …, defaultValue)
This is another variadic function - it can receive multiple input parameters. The first parameter subject is followed by (possibly multiple) pairs of value-return. Then there’s the last parameter defaultValue
The function works as a simple decision making table. If subject equals v1, then r1 is returned. Else, if subject equals v2, then r2 is returned. If subject doesn’t match any v* parameters, defaultValue is returned. It basically works as series of if-else statements.
restrictions
- types of all
v*parameters must be the same, and it must match type ofsubject - types of all
r*parameters must be the same, and it must match type ofdefaultValue
return type:
the same type as defaultValue parameter
examples
decode(1, 0, 'zero', 1, 'one', 2, 'two', 'too much')
decode(0, 0, 'zero', 1, 'one', 2, 'two', 'too much')
decode(5, 0, 'zero', 1, 'one', 2, 'two', 'too much')
returns
one
zero
too much
real life example
decode(p.quantity, 0, 'not in stock', 1, 'last', 2, 'in stock')
~~~ is equivalent to ~~~
if(p.quantity = 0, 'not in stock', if(p.quantity = 1, 'last', 'in stock'))