From f1272644191124975c9e00c0b5e25d701ceaed6d Mon Sep 17 00:00:00 2001 From: Brenda Sukh Date: Mon, 23 Nov 2020 18:45:40 -0500 Subject: [PATCH] Add aggregation sum util --- plugins/cost-insights/src/utils/change.ts | 9 +++++---- plugins/cost-insights/src/utils/sum.ts | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 plugins/cost-insights/src/utils/sum.ts diff --git a/plugins/cost-insights/src/utils/change.ts b/plugins/cost-insights/src/utils/change.ts index 1718462948..fc50439aad 100644 --- a/plugins/cost-insights/src/utils/change.ts +++ b/plugins/cost-insights/src/utils/change.ts @@ -23,6 +23,7 @@ import { MetricData, Duration, DEFAULT_DATE_FORMAT, + DateAggregation, } from '../types'; import dayjs, { OpUnitType } from 'dayjs'; import duration from 'dayjs/plugin/duration'; @@ -54,9 +55,9 @@ export function getComparedChange( duration: Duration, lastCompleteBillingDate: string, // YYYY-MM-DD, ): ChangeStatistic { - const ratio = dailyCost.change.ratio - metricData.change.ratio; + const ratio = dailyCost.change!.ratio - metricData.change.ratio; const previousPeriodTotal = getPreviousPeriodTotalCost( - dailyCost, + dailyCost.aggregation, duration, lastCompleteBillingDate, ); @@ -67,7 +68,7 @@ export function getComparedChange( } export function getPreviousPeriodTotalCost( - dailyCost: Cost, + aggregation: DateAggregation[], duration: Duration, inclusiveEndDate: string, ): number { @@ -83,7 +84,7 @@ export function getPreviousPeriodTotalCost( const nextPeriodStart = dayjs(startDate).add(amount, type); // Add up costs that incurred before the start of the next period. - return dailyCost.aggregation.reduce((acc, costByDate) => { + return aggregation.reduce((acc, costByDate) => { return dayjs(costByDate.date).isBefore(nextPeriodStart) ? acc + costByDate.amount : acc; diff --git a/plugins/cost-insights/src/utils/sum.ts b/plugins/cost-insights/src/utils/sum.ts new file mode 100644 index 0000000000..6fc181fea5 --- /dev/null +++ b/plugins/cost-insights/src/utils/sum.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Spotify AB + * + * 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. + */ + +import { DateAggregation } from '../types'; + +export const aggregationSum = (aggregation: DateAggregation[]) => + aggregation.reduce((total, curAgg) => total + curAgg.amount, 0);