Commits

Juri Pakaste  committed c63393d

added reduceWithInitialValue:block:

  • Participants
  • Parent commits 0151d82

Comments (0)

Files changed (2)

File ScalarArray/ScalarArray.h

 typedef t (^ Scalar ## ct ## ValueFromObject)(id object); \
 typedef BOOL (^ Scalar ## ct ## TestEqual)(t v0, t v1); \
 typedef NSUInteger (^ Scalar ## ct ## ValueHash)(t value); \
+typedef t (^ Scalar ## ct ## ReduceBlock)(t value, t acc); \
 @interface Scalar ## ct ## Array : NSObject \
 -(void)addValue:(t)val; \
 -(void)addValuesFromArray:(NSArray*)array withBlock:(Scalar ## ct ## ValueFromObject)block; \
 -(void)enumerateValuesUntilFalseWithBlock:(Scalar ## ct ## ArrayEnumerateUntilBlock)block; \
 -(void)insertValue:(t)value atIndex:(NSUInteger)index; \
 -(t)lastValue; \
+-(t)reduceWithInitialValue:(t)initial block:(Scalar ## ct ## ReduceBlock)block; \
 -(void)removeAllValues; \
 -(void)removeValueAtIndex:(NSUInteger)index; \
 -(void)removeValuesInRange:(NSRange)range; \
         if (! cont) break; \
     } \
 } \
+-(t)reduceWithInitialValue:(t)initial block:(Scalar ## ct ## ReduceBlock)block { \
+    __block t acc = initial; \
+    [self enumerateValuesWithBlock:^(t val) { \
+        acc = block(val, acc); \
+    }]; \
+    return acc; \
+} \
 -(void)removeAllValues { \
     [data setLength:0]; \
     count = 0; \

File Tests/ScalarArrayTest.m

 }
 
 
+-(void)testReduceEmpty
+{
+    ScalarDoubleArray *da0 = [[[ScalarDoubleArray alloc] init] autorelease];
+	double r = [da0 reduceWithInitialValue:0.0 block:^double(double value, double acc) {
+		return value + acc;
+	}];
+	GHAssertEquals(r, 0.0, @"Wrong return value for empty sum");
+}
+
+
+-(void)testReduceOne
+{
+    ScalarDoubleArray *da0 = [[[ScalarDoubleArray alloc] init] autorelease];
+	[da0 addValue:1.0];
+	double r = [da0 reduceWithInitialValue:0.0 block:^double(double value, double acc) {
+		return value + acc;
+	}];
+	GHAssertEqualsWithAccuracy(r, 1.0, 0.001, @"Wrong return value for sum of one");
+}
+
+
+-(void)testReduceTwo
+{
+    ScalarDoubleArray *da0 = [[[ScalarDoubleArray alloc] init] autorelease];
+	[da0 addValue:1.0];
+	[da0 addValue:2.5];
+	double r = [da0 reduceWithInitialValue:0.0 block:^double(double value, double acc) {
+		return value + acc;
+	}];
+	GHAssertEqualsWithAccuracy(r, 3.5, 0.001, @"Wrong return value for sum of two");
+}
+
+-(void)testReduceThree
+{
+    ScalarDoubleArray *da0 = [[[ScalarDoubleArray alloc] init] autorelease];
+	[da0 addValue:1.0];
+	[da0 addValue:2.5];
+	[da0 addValue:3.7];
+	double r = [da0 reduceWithInitialValue:0.0 block:^double(double value, double acc) {
+		return value + acc;
+	}];
+	GHAssertEqualsWithAccuracy(r, 7.2, 0.001, @"Wrong return value for sum of three");
+}
+
 @end