Skip to content

Commit

Permalink
adding prelim min_by
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Joldersma committed Jul 30, 2012
1 parent 01d7ca7 commit 4d26123
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Languages/Ruby/Libraries/Builtins/Enumerable.cs
Expand Up @@ -588,6 +588,46 @@ public static class Enumerable {
#endregion

#region TODO: min_by, max_by, minmax_by

[RubyMethod("min_by")]
public static object GetMinBy(CallSiteStorage<EachSite>/*!*/ each, ComparisonStorage/*!*/ comparisonStorage, BlockParam comparer, object self) {

bool firstItem = true;
object result = null;
object resultValue = null;

Each(each, self, Proc.Create(each.Context, delegate(BlockParam/*!*/ selfBlock, object _, object item) {
if (firstItem) {
result = item;
object firstBlockResult;
comparer.Yield(item, out blockResult);
resultValue = blockResult;
firstItem = false;
return null;
}

Protocols.Compare(comparisonStorage, left, right);

object itemBlockResult;
comparer.Yield (item, out itemBlockResult);
object compareBlockResult;
int? compareResult = CompareItems(comparisonStorage, itemBlockResult, resultValue, comparer, out compareBlockResult);
if (compareResult == null) {
result = compareBlockResult;
return selfBlock.PropagateFlow(comparer, blockResult);
}

// Check if we have found the new minimum or maximum (+1 to select max, -1 to select min)
if (compareResult == comparisonValue) {
result = item;
resultValue = itemBlockResult;
}

return null;
}));

return result;
}

#endregion

Expand Down

0 comments on commit 4d26123

Please sign in to comment.