UNPKG

everyutil

Version:

A comprehensive library of lightweight, reusable utility functions for JavaScript and TypeScript, designed to streamline common programming tasks such as string manipulation, array processing, date handling, and more.

21 lines (20 loc) 796 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.movingAverage = void 0; /** * Calculates the simple moving average (SMA) of an array with a given window size. * For example, movingAverage([1,2,3,4,5], 3) returns [2,3,4]. * @author @dailker * @param {number[]} array - The input array of numbers. * @param {number} windowSize - The size of the moving window. * @returns {number[]} The array of moving averages. */ function movingAverage(array, windowSize) { const result = []; for (let i = 0; i <= array.length - windowSize; i++) { const window = array.slice(i, i + windowSize); result.push(window.reduce((a, b) => a + b, 0) / window.length); } return result; } exports.movingAverage = movingAverage;