- (NSArray *)_map:(id(^)(id))handle { if (!handle || !self) return self; NSMutableArray *arr = NSMutableArray.array; for (id obj in self) { id new = handle(obj); [arr addObject:new]; } return arr.copy; }
- (id)_reduce:(id(^)(id, id))handle initial:(id)initial { if (!handle || !self || !initial) return self; if (self.count <1) return initial; id value = initial; for (id obj in self) { value = handle(value, obj); } return value; }
/** Usages: */ NSArray *numbers = @[@3,@2,@10]; id result = [numbers _reduce:^id _Nonnull(NSNumber *obj1, NSNumber *obj2) { return @(obj1.intValue * obj2.intValue); } initial:@1]; NSLog(@"%@", result); // Prints "60"
NSArray *words = @[@"hello", @"world", @"good", @"night"]; id result = [words _reduce:^id _Nonnull(NSString *obj1, NSString *obj2) { return [NSString stringWithFormat:@"%@%@", obj1, obj2]; } initial:@""]; NSLog(@"%@", result); // Prints "helloworldgoodnight"