| 1 |
// Copyright 2017 The Closure Library Authors. All Rights Reserved. |
| 2 |
// |
| 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 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS-IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
/** |
| 16 |
* @fileoverview Provides some utility methods for calling delegate lists with |
| 17 |
* common "calling conventions". |
| 18 |
* |
| 19 |
* @see goog.delegate.DelegateRegistry |
| 20 |
*/ |
| 21 |
|
| 22 |
goog.module('goog.delegate.delegates'); |
| 23 |
|
| 24 |
|
| 25 |
/** |
| 26 |
* Calls the first delegate, or returns undefined if none are given. |
| 27 |
* @param {!Array<T>} delegates |
| 28 |
* @param {function(T): R} mapper |
| 29 |
* @return {R|undefined} |
| 30 |
* @template T, R |
| 31 |
*/ |
| 32 |
exports.callFirst = (delegates, mapper) => { |
| 33 |
return delegates.length > 0 ? mapper(delegates[0]) : undefined; |
| 34 |
}; |
| 35 |
|
| 36 |
|
| 37 |
/** |
| 38 |
* Calls delegates until one returns a defined, non-null result. Returns |
| 39 |
* undefined if no such element is found. |
| 40 |
* @param {!Array<T>} delegates |
| 41 |
* @param {function(T): R|undefined} mapper |
| 42 |
* @return {R|undefined} |
| 43 |
* @template T, R |
| 44 |
*/ |
| 45 |
exports.callUntilDefinedAndNotNull = (delegates, mapper) => { |
| 46 |
for (const delegate of delegates) { |
| 47 |
const result = mapper(delegate); |
| 48 |
if (result != null) return result; |
| 49 |
} |
| 50 |
return undefined; |
| 51 |
}; |
| 52 |
|
| 53 |
|
| 54 |
/** |
| 55 |
* Calls delegates until one returns a truthy result. Returns false if no such |
| 56 |
* element is found. |
| 57 |
* @param {!Array<T>} delegates |
| 58 |
* @param {function(T): R} mapper |
| 59 |
* @return {boolean|R} |
| 60 |
* @template T, R |
| 61 |
*/ |
| 62 |
exports.callUntilTruthy = (delegates, mapper) => { |
| 63 |
for (const delegate of delegates) { |
| 64 |
const result = mapper(delegate); |
| 65 |
if (result) return result; |
| 66 |
} |
| 67 |
return false; |
| 68 |
}; |