From dad49354aa292bbfcfdfe49354e0f88fc0bd4523 Mon Sep 17 00:00:00 2001 From: Martin Carlberg Date: Fri, 18 Oct 2019 13:01:04 +0200 Subject: [PATCH] Fixed: CPSet enumerateObjectsUsingBlock: will honor the stop variable Test case also added. Deprecated the very old behaviour that the block could return YES to abort the enumeration. --- Foundation/CPSet/_CPSet.j | 15 +++++++++------ Tests/Foundation/CPSetTest.j | 30 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/Foundation/CPSet/_CPSet.j b/Foundation/CPSet/_CPSet.j index f80124c31..7f92ded22 100644 --- a/Foundation/CPSet/_CPSet.j +++ b/Foundation/CPSet/_CPSet.j @@ -320,16 +320,19 @@ /*! Enumberates over the objects in a set using a given function. - @param aFunction a callback for each itteration, should be of the format: function(anObject). + @param aFunction a callback for each itteration, should be of the format: function(anObject, stop). */ -- (void)enumerateObjectsUsingBlock:(Function)aFunction +- (void)enumerateObjectsUsingBlock:(Function /*(id anObject, @ref BOOL stop)*/)aFunction { var object, - objectEnumerator = [self objectEnumerator]; + objectEnumerator = [self objectEnumerator], + shouldStop = NO; - while ((object = [objectEnumerator nextObject]) !== nil) - if (aFunction(object)) - break; + while (!shouldStop && (object = [objectEnumerator nextObject]) != nil) { + if (aFunction(object, @ref(shouldStop)) !== undefined) { + throw "DEPRECATED: The method enumerateObjectsUsingBlock: does not support returning a value in the block to stop the iteration. Please use the stop variable"; + } + } } // FIXME: stop is broken. diff --git a/Tests/Foundation/CPSetTest.j b/Tests/Foundation/CPSetTest.j index cdbee3ef9..e0b139d4c 100644 --- a/Tests/Foundation/CPSetTest.j +++ b/Tests/Foundation/CPSetTest.j @@ -368,4 +368,34 @@ [self assertTrue:[set2 member:dict2] === dict1]; } +- (void)testEnumateObjectsUsingBlock +{ + var input0 = [], + input1 = [CPSet setWithArray:[1, 3, "b"]], + output = [CPMutableDictionary dictionary], + idx = 0, + outputFunction = function(anObject) + { + [output setValue:anObject forKey:"" + idx++]; + }; + + [input0 enumerateObjectsUsingBlock:outputFunction]; + [self assert:0 equals:[output count] message:@"output when enumerating empty set"]; + + [input1 enumerateObjectsUsingBlock:outputFunction]; + [self assert:3 equals:[output count] message:@"output when enumerating input1"]; + + var stoppingFunction = function(anObject, stop) + { + [output setValue:anObject forKey:"" + idx++]; + if ([output count] > 1) + @deref(stop) = YES; + } + output = [CPMutableDictionary dictionary]; + idx = 0; + + [input1 enumerateObjectsUsingBlock:stoppingFunction]; + [self assert:2 equals:[output count] message:@"output when enumerating input1 and stopping after 2"]; +} + @end