npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

bbalgjs

v1.0.0

Published

JavaScript implementation of Baba algorithm for robustly determining status changes of objects to be tracked

Readme

bbalgjs

JavaScript implementation of the Baba algorithm for robustly determining status changes of objects to be tracked.

This is a JavaScript port of the original Python bbalg library.

Features

  • Robust state detection algorithm
  • Works in Node.js, browsers, and Electron (both main and renderer processes)
  • TypeScript support with full type definitions
  • Zero dependencies
  • Lightweight and performant

Installation

npm install bbalgjs

or

yarn add bbalgjs

Usage

Basic Usage in Node.js

const { stateVerdict, createFixedQueue } = require('bbalgjs');

// Create fixed-size queues for tracking history
const longHistory = createFixedQueue(10);  // Stores last 10 tracking results
const shortHistory = createFixedQueue(3);  // Stores last 3 tracking results

// Simulate tracking over time
const trackingResults = [false, false, true, true, true, true, true, true, true, true];

trackingResults.forEach(detected => {
  longHistory.push(detected);
  shortHistory.push(detected);

  // Always pass maxLength parameters (required)
  const result = stateVerdict(
    longHistory.toArray(), 
    shortHistory.toArray(),
    10,  // longMaxLength
    3    // shortMaxLength
  );
  
  // Returns all false until queues are full
  console.log(result);
});

ES Module Usage

import { stateVerdict, createFixedQueue } from 'bbalgjs';

// Same usage as CommonJS

Browser Usage

<script src="https://unpkg.com/bbalgjs/dist/bbalgjs.umd.min.js"></script>
<script>
  const { stateVerdict, createFixedQueue } = bbalgjs;

  // Use the functions
  const result = stateVerdict([true, true, false, true], [true, true], 4, 2);
  console.log(result);
</script>

TypeScript Usage

import { stateVerdict, createFixedQueue, StateVerdictResult, FixedQueue } from 'bbalgjs';

// TypeScript will infer types automatically
const longQueue: FixedQueue<boolean> = createFixedQueue(10);
const shortQueue: FixedQueue<boolean> = createFixedQueue(3);

// Process tracking data
const result: StateVerdictResult = stateVerdict(
  longQueue.toArray(),
  shortQueue.toArray(),
  10,  // longMaxLength
  3    // shortMaxLength
);

Electron Usage

The package works seamlessly in both Electron main and renderer processes:

Main Process:

// main.js
const { stateVerdict } = require('bbalgjs');

// Use in IPC handlers
ipcMain.handle('analyze-tracking', (event, longHistory, shortHistory, longMax, shortMax) => {
  return stateVerdict(longHistory, shortHistory, longMax, shortMax);
});

Renderer Process:

// renderer.js
const { stateVerdict, createFixedQueue } = require('bbalgjs');
// or with ES modules
import { stateVerdict, createFixedQueue } from 'bbalgjs';

// Use directly in renderer
const result = stateVerdict(longHistory, shortHistory, 10, 3);

API Reference

stateVerdict(longTrackingHistory, shortTrackingHistory, longMaxLength?, shortMaxLength?)

Determines the state of an object based on tracking history.

Parameters:

  • longTrackingHistory (Array): N historical tracking results (older to newer)
  • shortTrackingHistory (Array): M recent tracking results (older to newer)
  • longMaxLength (number, optional): Expected maximum length of long tracking history
  • shortMaxLength (number, optional): Expected maximum length of short tracking history

Note: If you provide one maxLength parameter, you must provide both.

Returns: Object with three properties:

  • stateInProgress (boolean): Whether the state is currently in progress
    • True when sum of long history ≥ N/2 AND sum of short history ≥ M-1
  • stateStartJudgment (boolean): Whether the state has just started
    • True when sum of long history = N/2 AND sum of short history ≥ M-1
  • stateEndJudgment (boolean): Whether the state has just ended
    • True when sum of long history = N/2 AND sum of short history ≤ 1

Throws: Error if:

  • Inputs are not arrays

Note:

  • Returns all false values if arrays are empty (matches Python bbalg behavior)
  • When maxLength parameters are provided, returns all false if history length is less than the specified maximum length

createFixedQueue(maxLength)

Creates a fixed-size queue (deque) that maintains a maximum length.

Parameters:

  • maxLength (number): Maximum number of items the queue can hold

Returns: Object with methods:

  • push(item): Add an item to the queue (removes oldest if at capacity)
  • toArray(): Get all items as an array
  • length: Current number of items (getter)
  • maxLength: Maximum capacity (getter)

Throws: Error if maxLength is not a positive integer

Practical Examples

Object Detection Tracking

const { stateVerdict, createFixedQueue } = require('bbalgjs');

class ObjectTracker {
  constructor() {
    this.longHistory = createFixedQueue(20);
    this.shortHistory = createFixedQueue(5);
  }

  processFrame(objectDetected) {
    this.longHistory.push(objectDetected);
    this.shortHistory.push(objectDetected);

    if (this.longHistory.length < 2 || this.shortHistory.length < 2) {
      return null; // Not enough data yet
    }

    const verdict = stateVerdict(
      this.longHistory.toArray(),
      this.shortHistory.toArray(),
      20,  // longMaxLength
      5    // shortMaxLength
    );

    if (verdict.stateStartJudgment) {
      console.log('Object tracking started!');
    } else if (verdict.stateEndJudgment) {
      console.log('Object tracking ended!');
    } else if (verdict.stateInProgress) {
      console.log('Object is being tracked...');
    }

    return verdict;
  }
}

// Usage
const tracker = new ObjectTracker();

// Simulate object detection over 30 frames
for (let i = 0; i < 30; i++) {
  // Object appears after frame 10 and disappears after frame 20
  const detected = i >= 10 && i < 20;
  const result = tracker.processFrame(detected);

  if (result) {
    console.log(`Frame ${i}:`, result);
  }
}

Motion Detection

const { stateVerdict, createFixedQueue } = require('bbalgjs');

class MotionDetector {
  constructor(sensitivity = { long: 15, short: 4 }) {
    this.longHistory = createFixedQueue(sensitivity.long);
    this.shortHistory = createFixedQueue(sensitivity.short);
  }

  analyzeMotion(motionValue, threshold = 0.1) {
    // Convert motion value to boolean based on threshold
    const motionDetected = motionValue > threshold;

    this.longHistory.push(motionDetected);
    this.shortHistory.push(motionDetected);

    if (this.longHistory.length < 2 || this.shortHistory.length < 2) {
      return { motion: 'initializing' };
    }

    const verdict = stateVerdict(
      this.longHistory.toArray(),
      this.shortHistory.toArray(),
      20,  // longMaxLength
      5    // shortMaxLength
    );

    if (verdict.stateStartJudgment) {
      return { motion: 'started', event: true };
    } else if (verdict.stateEndJudgment) {
      return { motion: 'ended', event: true };
    } else if (verdict.stateInProgress) {
      return { motion: 'ongoing', event: false };
    } else {
      return { motion: 'idle', event: false };
    }
  }
}

State Machine Integration

const { stateVerdict, createFixedQueue } = require('bbalgjs');

class StateMachine {
  constructor() {
    this.states = new Map();
  }

  addState(name, historyConfig = { long: 10, short: 3 }) {
    this.states.set(name, {
      longHistory: createFixedQueue(historyConfig.long),
      shortHistory: createFixedQueue(historyConfig.short),
      active: false
    });
  }

  updateState(name, condition) {
    const state = this.states.get(name);
    if (!state) throw new Error(`State ${name} not found`);

    state.longHistory.push(condition);
    state.shortHistory.push(condition);

    if (state.longHistory.length >= 2 && state.shortHistory.length >= 2) {
      const verdict = stateVerdict(
        state.longHistory.toArray(),
        state.shortHistory.toArray()
      );

      const wasActive = state.active;
      state.active = verdict.stateInProgress;

      return {
        state: name,
        active: state.active,
        changed: wasActive !== state.active,
        verdict
      };
    }

    return null;
  }
}

// Usage
const machine = new StateMachine();
machine.addState('user_active', { long: 30, short: 5 });
machine.addState('high_cpu', { long: 20, short: 4 });

// Monitor states
setInterval(() => {
  const userActive = machine.updateState('user_active', isUserActive());
  const highCpu = machine.updateState('high_cpu', getCpuUsage() > 80);

  if (userActive?.changed) {
    console.log('User activity state changed:', userActive.active);
  }

  if (highCpu?.verdict.stateStartJudgment) {
    console.log('High CPU usage detected!');
  }
}, 1000);

Algorithm Details

The Baba algorithm uses two sliding windows of different sizes to make robust determinations about state changes:

  1. Long History: Provides context and stability
  2. Short History: Provides responsiveness to recent changes

The algorithm calculates three judgments:

  • State in Progress: Indicates a stable, ongoing state
  • State Start: Detects the transition into a new state
  • State End: Detects the transition out of a state

This dual-window approach helps filter out noise and provides reliable state detection even in the presence of occasional false positives or negatives.

Build from Source

# Clone the repository
git clone https://github.com/PINTO0309/bbalgjs.git
cd bbalgjs

# Install dependencies
npm install

# Run tests
npm test

# Build the package
npm run build

License

MIT License - see LICENSE file for details.

Credits

Original Python implementation by PINTO0309.