A representative but thoroughly useless and unscientific way to see how people write short pieces of code.
Write a function, method, or other similar construct in your favorite language that:
- accepts an array
arr
and a valuev
- returns the element in
arr
whose successor isv
, if there is such an element; otherwise return nothing
Test cases:
find_before([5, 6, 7], 6)
# => 5
find_before([5, 6, 7], 7)
# => 6
find_before([5, 6, 7], 5)
# => nothing
find_before([5, 6, 7], 999)
# => nothing
If I could change the specification, I'd alter it to take a "value not found" parameter which is returned if the value isn't found. A test case would thus become:
This would be in keeping with Nullable<T>.GetValueOrDefault(T) and other methods. C# implementation could thus become:
I would not expect an exception to be thrown; exceptions are for errors and exceptions are (generally) slow, so they should be avoided for common errors. For example, Stream.Read() returns 0 on end-of-stream instead of throwing an EndOfStreamException, as hitting end-of-stream is a common condition.