FBLPromise+Reduce.m 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. Copyright 2018 Google Inc. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at:
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #import "FBLPromise+Reduce.h"
  14. #import "FBLPromisePrivate.h"
  15. @implementation FBLPromise (ReduceAdditions)
  16. - (FBLPromise *)reduce:(NSArray *)items combine:(FBLPromiseReducerBlock)reducer {
  17. return [self onQueue:FBLPromise.defaultDispatchQueue reduce:items combine:reducer];
  18. }
  19. - (FBLPromise *)onQueue:(dispatch_queue_t)queue
  20. reduce:(NSArray *)items
  21. combine:(FBLPromiseReducerBlock)reducer {
  22. NSParameterAssert(queue);
  23. NSParameterAssert(items);
  24. NSParameterAssert(reducer);
  25. FBLPromise *promise = self;
  26. for (id item in items) {
  27. promise = [promise chainOnQueue:queue
  28. chainedFulfill:^id(id value) {
  29. return reducer(value, item);
  30. }
  31. chainedReject:nil];
  32. }
  33. return promise;
  34. }
  35. @end
  36. @implementation FBLPromise (DotSyntax_ReduceAdditions)
  37. - (FBLPromise * (^)(NSArray *, FBLPromiseReducerBlock))reduce {
  38. return ^(NSArray *items, FBLPromiseReducerBlock reducer) {
  39. return [self reduce:items combine:reducer];
  40. };
  41. }
  42. - (FBLPromise * (^)(dispatch_queue_t, NSArray *, FBLPromiseReducerBlock))reduceOn {
  43. return ^(dispatch_queue_t queue, NSArray *items, FBLPromiseReducerBlock reducer) {
  44. return [self onQueue:queue reduce:items combine:reducer];
  45. };
  46. }
  47. @end