# all files / src/aggregators/ aggregate.js

100% Statements 55/55
100% Branches 26/26
100% Functions 13/13
100% Lines 53/53
2 statements, 1 branch Ignored

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261

    73×

    1×

    1×

    1×

    1×

    9×
    14×

    9×
    12×
    9×
    2×

    9×

    8×
    8×
    12×
    1×

    11×

    7×

    13×

    13×

    3×

    10×

    1×

    9×
    1×

    8×

    5×
    5×

    2×
    2×

    1×
    1×

    8×

    2×

    5×

    6×

    6×

    6×
    6×
    6×

    6×

    8×
    1×

    1×

    8×
    1×

    7×

    7×
    2×

    5×

    6×

    1×

    1×
     /**
     * @license
     * Copyright 2016 Google Inc. All rights reserved.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    'use strict';

    class Aggregate {

      /**
       * The types of aggregation supported by Lighthouse. These are used by the HTML Report
       * to broadly classify the outputs. Most of the audits will be included in aggregations
       * that are of TYPES.PWA, but any non-PWA best practices should be in aggregators of
       * TYPES.BEST_PRACTICE.
       */
      static get TYPES() {
        return {
          PWA: {
            name: 'Progressive Web App',
            contributesToScore: true
          },
          BEST_PRACTICE: {
            name: 'Best Practices',
            contributesToScore: false
          },
          PERFORMANCE_METRICS: {
            name: 'Performance Metrics',
            contributesToScore: false
          }
        };
      }

      /**
       * @throws {Error}
       * @return {string} The name for this aggregation.
       */
      static get name() {
        throw new Error('Aggregate name must be overridden');
      }

      /**
       * @throws {Error}
       * @return {string} The short name for this aggregation.
       */
      static get description() {
        throw new Error('Aggregate description must be overridden');
      }

      /**
       * @throws {Error}
       * @return {Object} The type of aggregation.
       */
      static get type() {
        throw new Error('Aggregate type must be overridden');
      }

      /**
       * @throws {Error}
       * @return {!AggregationCriteria} The criteria for this aggregation.
       */
      static get criteria() {
        throw new Error('Aggregate criteria must be overridden');
      }

      /**
       * @private
       * @param {!Array<!AuditResult>} results
       * @param {!AggregationCriteria} expected
       * @return {!Array<!AuditResult>}
       */
      static _filterResultsByAuditNames(results, expected) {
        const expectedNames = Object.keys(expected);
        return results.filter(r => expectedNames.indexOf(/** @type {string} */ (r.name)) !== -1);
      }

      /**
       * @private
       * @param {!AggregationCriteria} expected
       * @return {number}
       */
      static _getTotalWeight(expected) {
        const expectedNames = Object.keys(expected);
        let weight = expectedNames.reduce((last, e) => last + expected[e].weight, 0);
        if (weight === 0) {
          weight = 1;
        }

        return weight;
      }

      /**
       * @private
       * @param {!Array<!AuditResult>} results
       * @return {!Object<!AuditResult>}
       */
      static _remapResultsByName(results) {
        const remapped = {};
        results.forEach(r => {
          if (remapped[r.name]) {
            throw new Error(`Cannot remap: ${r.name} already exists`);
          }

          remapped[r.name] = r;
        });
        return remapped;
      }

      /**
       * Converts each raw audit output to a weighted value for the aggregation.
       * @private
       * @param {!AuditResult} result The audit's output value.
       * @param {!AggregationCriterion} expected The aggregation's expected value and weighting for this result.
       * @return {number} The weighted result.
       */
      static _convertToWeight(result, expected) {
        let weight = 0;

        if (typeof expected === 'undefined' ||
            typeof expected.value === 'undefined' ||
            typeof expected.weight === 'undefined') {
          return weight;
        }

        if (typeof result === 'undefined' ||
            typeof result.value === 'undefined') {
          return weight;
        }

        if (typeof result.value !== typeof expected.value) {
          return weight;
        }

        switch (typeof expected.value) {
          case 'boolean':
            weight = this._convertBooleanToWeight(result.value, expected.value, expected.weight);
            break;

          case 'number':
            weight = this._convertNumberToWeight(result.value, expected.value, expected.weight);
            break;

          default:
            weight = 0;
            break;
        }

        return weight;
      }

      /**
       * Converts a numeric result to a weight.
       * @param {number} resultValue The result.
       * @param {number} expectedValue The expected value.
       * @param {number} weight The weight to assign.
       * @return {number} The final weight.
       */
      static _convertNumberToWeight(resultValue, expectedValue, weight) {
        return (resultValue / expectedValue) * weight;
      }

      /**
       * Converts a boolean result to a weight.
       * @param {boolean} resultValue The result.
       * @param {boolean} expectedValue The expected value.
       * @param {number} weight The weight to assign.
       * @return {number} The final weight.
       */
      static _convertBooleanToWeight(resultValue, expectedValue, weight) {
        return (resultValue === expectedValue) ? weight : 0;
      }

      /**
       * Compares the set of audit results to the expected values.
       * @param {!Array<!AuditResult>} results The audit results.
       * @param {!AggregationCriteria} expected The aggregation's expected values and weighting.
       * @param {!AggregationType} aggregationType The type of aggregator we have (e.g. PWA, Best Practices, etc.)
       * @return {!AggregationItem} The aggregation score.
       */
      static compare(results, expected, aggregationType) {
        const expectedNames = Object.keys(expected);

        // Filter down and remap the results to something more comparable to
        // the expected set of results.
        const filteredAndRemappedResults =
            Aggregate._remapResultsByName(
              Aggregate._filterResultsByAuditNames(results, expected)
            );
        const maxScore = Aggregate._getTotalWeight(expected);
        const subItems = [];
        let overallScore = 0;

        // Step through each item in the expected results, and add them
        // to the overall score and add each to the subItems list.
        expectedNames.forEach(e => {
          /* istanbul ignore if */
          // TODO(paullewis): Remove once coming soon audits have landed.
          Iif (expected[e].comingSoon) {
            subItems.push({
              value: '¯\\_(ツ)_/¯', // TODO(samthor): Patch going to Closure, String.raw is badly typed
              name: 'coming-soon',
              category: expected[e].category,
              description: expected[e].description,
              comingSoon: true
            });

            return;
          }

          if (!filteredAndRemappedResults[e]) {
            return;
          }

          subItems.push(filteredAndRemappedResults[e]);

          // Only add to the score if this aggregation contributes to the
          // overall score.
          if (!aggregationType.contributesToScore) {
            return;
          }

          overallScore += Aggregate._convertToWeight(
              filteredAndRemappedResults[e],
              expected[e]);
        });

        return {
          overall: (overallScore / maxScore),
          subItems: subItems
        };
      }

      /**
       * Aggregates all the results.
       * @param {!Array<!AuditResult>} results
       * @return {!Aggregation}
       */
      static aggregate(results) {
        return {
          name: this.name,
          shortName: this.shortName,
          description: this.description,
          type: this.type,
          score: Aggregate.compare(results, this.criteria, this.type)
        };
      }
    }

    module.exports = Aggregate;