🚀 Big News:Socket Has Acquired Secure Annex.Learn More →
Socket
Book a DemoSign in
Socket

sliding-window-max

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sliding-window-max

[![chrvadala](https://img.shields.io/badge/website-chrvadala-orange.svg)](https://chrvadala.github.io) [![Test](https://github.com/chrvadala/sliding-window-max/workflows/Test/badge.svg)](https://github.com/chrvadala/sliding-window-max/actions) [![Coverage

latest
Source
npmnpm
Version
1.1.0
Version published
Weekly downloads
26
62.5%
Maintainers
1
Weekly downloads
 
Created
Source

sliding-window-max

chrvadala Test Coverage Status npm Downloads Donate

Given a stream of data, this algorithm returns (for every added value) the current max value.

It uses a strategy that:

  • Stores at most a number of values defined by the window size
  • Performs a rolling max calculation

Example

const SlidingWindowMax = require('sliding-window-max')

const windowSize = 3

const slidingWindowMax = new SlidingWindowMax(windowSize)
slidingWindowMax.add(0) // returns null
slidingWindowMax.add(5) // returns null
slidingWindowMax.add(10)// returns 10
slidingWindowMax.add(7) // returns 10
slidingWindowMax.add(8) // returns 10
slidingWindowMax.add(5) // returns 8
slidingWindowMax.add(3) // returns 8
slidingWindowMax.add(4) // returns 5
//etc ...
VALUEMax
[0] 5 10 7 8 5 3 4null
[0 5] 10 7 8 5 3 4null
[0 5 10] 7 8 5 3 410
0 [5 10 7] 8 5 3 410
0 5 [10 7 8] 5 3 410
0 5 10 [7 8 5] 3 48
0 5 10 7 [8 5 3] 48
0 5 10 7 8 [5 3 4]5
......

Reference

new SlidingWindowMax(windowSize, options)

ParamDefaultDescription
windowSizerequiredDefines how many values should be considered to calculate the max
options.comparator(a, b) => b - aOverride the custom comparator function
options.waitFullRangetrueIf false the functions returns the max value also if the window size hasn't been reached yet

add(value)

Evaluate a new value and returns the calculated max value

Credits

I made this algorithm starting from this code https://github.com/chihungyu1116/leetcode-javascript/blob/master/239%20Sliding%20Window%20Maximum.js. My requirements were a bit different. The leetcode algorithm requires that all the data are known before it starts. With sliding-window-max you can:

  • evaluate the data as soon as they are produced
  • evaluate big array using less memory

Changelog

  • 0.x - Beta version
  • 1.0 - First official version
  • 1.1 - Migrates to gh-workflows; Upgrades deps

Contributors

FAQs

Package last updated on 01 Jun 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts