Skip to content

Instantly share code, notes, and snippets.

@fj
Created July 16, 2012 12:33
Show Gist options
  • Save fj/3122440 to your computer and use it in GitHub Desktop.
Save fj/3122440 to your computer and use it in GitHub Desktop.

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 value v
  • returns the element in arr whose successor is v, 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
@jonpryor
Copy link

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:

find_before([5, 6, 7], 5, nil)
# => nil

This would be in keeping with Nullable<T>.GetValueOrDefault(T) and other methods. C# implementation could thus become:

public static T FindBeforeOrDefault<T>(this IEnumerable<T> values, T value, T defaultValue = default (T), EqualityComparer<T> comparer = null)
{
    comparer    = comparer ?? EqualityComparer<T>.Default;
    return values.ContiguousSubsequences (2)
        .FirstOrDefault<IEnumerable<T>> (e => comparer.Equals (value, e.ElementAt (1)))
        .With (e => e == null ? defaultValue : e.First ());
}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment