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

creb-js

v1.5.0

Published

Chemical Reaction Equation Balancer - JavaScript Library

Downloads

36

Readme

CREB-JS: Chemical Reaction Equation Balancer

CI npm version License: AGPL v3 TypeScript Demo

A comprehensive TypeScript/JavaScript library for balancing chemical equations with thermodynamic analysis, performing stoichiometric calculations, and accessing chemical compound data through PubChem integration. All features are fully functional with robust validation and user-friendly interfaces.

🚀 Features

Core CREB Features

  • 🧪 Balance chemical equations automatically with advanced algorithms
  • ⚖️ Calculate stoichiometric ratios for complex reactions
  • 🧮 Compute molar weights for any chemical formula
  • 📊 Perform mole and mass calculations with detailed results
  • 🔬 Support for complex formulas with parentheses and nested groups
  • Robust validation with helpful error messages and pre-filled examples

Enhanced PubChem Integration (creb-pubchem-js)

  • 🧬 Search compounds by name, CID, SMILES, or InChI
  • 📋 Retrieve detailed properties (molecular weight, formula, IUPAC names)
  • 🔍 Compare compounds with side-by-side analysis
  • ⚗️ Enhanced stoichiometry with real compound data
  • 🌐 Type-safe API with comprehensive error handling
  • 🎯 Smart auto-population between related features

Phase 2: Enhanced Classes (NEW!)

  • 🆕 EnhancedChemicalEquationBalancer - PubChem-integrated balancing with compound validation
  • 🆕 EnhancedStoichiometry - Advanced calculations with real compound data and accuracy verification
  • Mass balance validation using accurate PubChem molecular weights
  • 🏪 Intelligent caching to minimize API calls and improve performance
  • 🔄 Graceful degradation - works with or without PubChem package installed
  • 💡 Alternative suggestions for unknown or misspelled compounds

Phase 3: Thermodynamics Module (NEW! 🔥)

  • 🌡️ Thermodynamic calculations - Calculate ΔH°, ΔS°, and ΔG° for chemical reactions
  • ⚖️ Spontaneity prediction - Determine if reactions are thermodynamically favorable
  • 📊 Temperature analysis - Study how temperature affects reaction thermodynamics
  • 🔥 Energy analysis - Calculate heat released/absorbed in reactions
  • 🧬 Biochemical reactions - Analyze glucose combustion and metabolic pathways
  • 📚 Scientific accuracy - Based on NIST and CRC Handbook reference data
  • 🚀 Thermodynamics-Integrated Balancer - Revolutionary tool combining equation balancing with comprehensive thermodynamic analysis, safety assessment, and optimization recommendations

🎮 Try the Live Demos

Main Demo - Interactive Web Interface ✨

  • Professional UI with navigation menu and responsive design
  • All CREB features working seamlessly with pre-filled examples
  • PubChem integration for compound search, comparison, and analysis
  • Real-time calculations with comprehensive error handling
  • Immediate testing - all features have working examples ready to use

Test Suite - Comprehensive Testing

  • Automated test runner for all features
  • Manual testing interface
  • Integration and unit test results

Enhanced Demo - Phase 2 Showcase

  • Interactive Node.js demonstration of enhanced features
  • PubChem integration examples with graceful fallbacks
  • Compound validation and molecular weight verification
  • Run with: node demos/enhanced-demo.js

📦 Installation

# Core CREB library
npm install creb-js

# PubChem integration (optional)  
npm install creb-pubchem-js

🏗️ Project Structure

CREB/
├── src/                 # Core CREB source code
├── packages/
│   └── pubchem-js/     # PubChem integration package
├── demos/              # Interactive demonstrations
│   ├── demo.html       # Main comprehensive demo
│   └── test-demo.html  # Test suite interface
├── examples/           # Code examples and usage patterns  
├── docs/              # Documentation and analysis
└── dist/              # Built library files

🎮 Try the Live Demos

Main Demo - Interactive Web Interface ✨

  • Professional UI with navigation menu and responsive design
  • All CREB features working seamlessly with pre-filled examples
  • PubChem integration for compound search, comparison, and analysis
  • Real-time calculations with comprehensive error handling
  • Immediate testing - all features have working examples ready to use

Test Suite - Comprehensive Testing

  • Automated test runner for all features
  • Manual testing interface
  • Integration and unit test results

✨ Recent Updates

Phase 2 Release: Enhanced CREB with PubChem Integration! 🎉

  • 🆕 New Enhanced Classes - EnhancedChemicalEquationBalancer and EnhancedStoichiometry
  • 🧬 PubChem Integration - Real compound data, molecular weight verification, and validation
  • Mass Balance Validation - Verify conservation using accurate PubChem molecular weights
  • 🏪 Smart Caching - Intelligent compound data caching to minimize API calls
  • 🔄 Graceful Degradation - Full functionality with or without PubChem package
  • 💡 Compound Suggestions - Alternative names for unknown or misspelled compounds
  • 📊 Molecular Weight Accuracy - Compare calculated vs. PubChem values with accuracy ratings
  • 🔬 Compound Comparison - Side-by-side analysis of chemical compounds

Previous Updates: All demo features are fully functional with enhanced user experience!

  • 🔧 Fixed all demo functionality with robust validation and error handling
  • Pre-filled working examples for immediate testing of all features
  • 🎯 Smart auto-population between equation balancer and stoichiometry calculator
  • 🛡️ Comprehensive input validation with helpful error messages
  • 📚 Improved library exports ensuring proper browser compatibility

Demo Features Ready to Use:

  1. Balance Chemical Equations - Pre-filled with Al + CuSO4 = Al2(SO4)3 + Cu
  2. Calculate Stoichiometry - Auto-populated from balanced equations
  3. Molar Weight Calculator - Ready with H2SO4 example
  4. PubChem Compound Search - Search by CID (2244), Name (aspirin), or SMILES
  5. Enhanced Stoichiometry - Glucose combustion with PubChem data
  6. Compound Comparison - Compare glucose vs fructose with detailed analysis

Phase 2 Enhanced Features (COMPLETE):

  1. Enhanced Chemical Intelligence - PubChem-validated compound data with mass balance verification ✅
  2. Compound Name Resolution - Balance equations using common chemical names ✅
  3. Enhanced Stoichiometry - Real compound data integration with molecular weight accuracy ✅
  4. Chemical Safety Information - GHS hazard warnings and safety classifications ✅

New Enhanced API:

// Enhanced chemical intelligence
const result = await balancer.balanceWithPubChemData("H2SO4 + NaOH = Na2SO4 + H2O");

// Balance using common names
const nameResult = await balancer.balanceByName(
  "sulfuric acid + sodium hydroxide = sodium sulfate + water"
);

// Safety warnings
const safetyResult = await balancer.balanceWithSafety("H2SO4 + NaOH = Na2SO4 + H2O");
console.log(safetyResult.safetyWarnings); // GHS hazard information

Quick Start

Core CREB Usage

import { ChemicalEquationBalancer, Stoichiometry } from 'creb-js';

// Balance a chemical equation
const balancer = new ChemicalEquationBalancer();
const balanced = balancer.balance('H2 + O2 = H2O');
console.log(balanced); // "2 H2 + O2 = 2 H2O"

// Calculate molar weight
const molarWeight = Stoichiometry.calculateMolarWeight('H2O');
console.log(molarWeight); // 18.015

// Perform stoichiometric calculations
const stoich = new Stoichiometry('2 H2 + O2 = 2 H2O');
const results = stoich.calculateFromMoles('H2', 2);
console.log(results);

Enhanced PubChem Integration

import { Compound } from 'creb-pubchem-js';

// Search compound by name
const compounds = await Compound.fromName('aspirin');
console.log(compounds[0].molecularFormula); // C9H8O4

// Get compound by CID
const water = await Compound.fromCid(962);
console.log(water.molecularWeight); // 18.015

// Search by SMILES
const benzene = await Compound.fromSmiles('C1=CC=CC=C1');
console.log(benzene[0].iupacName); // benzene

Phase 2: Enhanced Classes with PubChem Integration

import { 
  EnhancedChemicalEquationBalancer, 
  EnhancedStoichiometry 
} from 'creb-js';

// Enhanced equation balancing with compound validation
const balancer = new EnhancedChemicalEquationBalancer();
const result = await balancer.balanceWithPubChemData('C6H12O6 + O2 = CO2 + H2O');

console.log('Balanced:', result.equation);
console.log('Mass balanced:', result.validation?.massBalanced);

// Display compound information
if (result.compoundData) {
  for (const [species, info] of Object.entries(result.compoundData)) {
    console.log(`${species}: MW=${info.molecularWeight}, CID=${info.cid}`);
  }
}

// Enhanced stoichiometry with PubChem data
const stoich = new EnhancedStoichiometry();
await stoich.initializeWithValidation('2 H2 + O2 = 2 H2O');

const enhanced = await stoich.calculateFromMolesEnhanced('H2', 2);
console.log('Enhanced results with PubChem validation:', enhanced);

// Molecular weight with PubChem verification
const mwResult = await stoich.calculateMolarWeightEnhanced('H2O');
console.log(`H2O: Calculated=${mwResult.calculated}, PubChem=${mwResult.pubchem}`);
console.log(`Accuracy: ${mwResult.accuracy}`);

Phase 3: Thermodynamics Analysis

import { ThermodynamicsCalculator } from 'creb-js';

// Create thermodynamics calculator
const calculator = new ThermodynamicsCalculator();

// Analyze glucose combustion
const glucoseReaction = {
    reactants: [
        { formula: 'C6H12O6', coefficient: 1 },
        { formula: 'O2', coefficient: 6 }
    ],
    products: [
        { formula: 'CO2', coefficient: 6 },
        { formula: 'H2O', coefficient: 6 }
    ]
};

const result = calculator.calculateReactionThermodynamics(glucoseReaction, 298.15);
console.log('ΔH°:', result.enthalpy, 'kJ/mol');      // ~-2803 kJ/mol
console.log('ΔS°:', result.entropy, 'J/(mol·K)');    // ~262 J/(mol·K)  
console.log('ΔG°:', result.gibbsFreeEnergy, 'kJ/mol'); // ~-2726 kJ/mol
console.log('Spontaneous:', result.isSpontaneous);    // true

// Temperature effect analysis
const temperatures = [273.15, 298.15, 373.15, 500];
const tempAnalysis = calculator.calculateTemperatureDependence(glucoseReaction, temperatures);
tempAnalysis.forEach(data => {
    console.log(`T: ${data.temperature}K, ΔG: ${data.gibbsFreeEnergy.toFixed(1)} kJ/mol`);
});

NEW: Thermodynamics-Integrated Balancer 🚀

import { ThermodynamicsEquationBalancer } from 'creb-js';

// Create the revolutionary integrated balancer
const balancer = new ThermodynamicsEquationBalancer();

// Balance and analyze in one step
const equation = 'CH4 + O2 = CO2 + H2O';
const result = await balancer.balanceWithThermodynamics(equation);

// Get comprehensive analysis
console.log('✅ Balanced equation:', result.balanced);
console.log('🏷️ Reaction type:', result.reactionType);
console.log('⚡ Energy released:', result.energyReleased, 'kJ/mol');
console.log('✨ Feasibility:', result.feasibility);
console.log('⚠️ Safety level:', result.safetyLevel);
console.log('🔥 Spontaneous:', result.spontaneous);

// Safety and industrial insights
console.log('⚠️ Safety warnings:', result.safetyWarnings);
console.log('💡 Recommendations:', result.recommendations);
console.log('🏭 Industrial applications:', result.industrialApplications);

// Find optimal reaction conditions
const conditions = await balancer.findOptimalConditions(equation);
console.log('🌡️ Optimal temperature:', conditions.temperature, 'K');
console.log('🎯 Expected yield:', conditions.yield, '%');
console.log('🧠 Reasoning:', conditions.reasoning);

API Reference

ChemicalEquationBalancer

balance(equation: string): string

Balances a chemical equation and returns the balanced equation string.

Stoichiometry

calculateMolarWeight(formula: string): number

Calculates the molar weight of a chemical formula.

calculateFromMoles(species: string, moles: number): StoichiometryResult

Performs stoichiometric calculations starting from a given number of moles.

calculateFromGrams(species: string, grams: number): StoichiometryResult

Performs stoichiometric calculations starting from a given mass in grams.

Enhanced Classes (Phase 2)

EnhancedChemicalEquationBalancer

balanceWithPubChemData(equation: string): Promise<EnhancedBalancedEquation>

Balances a chemical equation with PubChem compound validation and enrichment.

getCompoundInfo(compoundName: string): Promise<CompoundInfo>

Retrieves detailed compound information from PubChem with caching.

EnhancedStoichiometry

initializeWithValidation(equation: string): Promise<ReactionAnalysis>

Initializes stoichiometry with PubChem compound validation and mass balance verification.

calculateFromMolesEnhanced(species: string, moles: number): Promise<EnhancedStoichiometryResult>

Enhanced calculation with PubChem molecular weight validation and accuracy assessment.

calculateMolarWeightEnhanced(formula: string): Promise<MolarWeightResult>

Calculates molecular weight with PubChem verification and accuracy rating.

Examples

Balance Complex Equations

const balancer = new ChemicalEquationBalancer();

// Simple equation
console.log(balancer.balance('Fe + O2 = Fe2O3'));
// Output: "4 Fe + 3 O2 = 2 Fe2O3"

// Complex equation with parentheses
console.log(balancer.balance('Ca(OH)2 + HCl = CaCl2 + H2O'));
// Output: "Ca(OH)2 + 2 HCl = CaCl2 + 2 H2O"

Stoichiometric Calculations

const stoich = new Stoichiometry('2 H2 + O2 = 2 H2O');

// Calculate from moles
const fromMoles = stoich.calculateFromMoles('H2', 4);
console.log(fromMoles);
// {
//   reactants: { H2: { moles: 4, grams: 8.064 }, O2: { moles: 2, grams: 63.998 } },
//   products: { H2O: { moles: 4, grams: 72.06 } }
// }

// Calculate from grams
const fromGrams = stoich.calculateFromGrams('O2', 32);
console.log(fromGrams);

🧪 Testing & Demos

Running Tests

# Run all tests (CREB + PubChem)
npm test

# Run only CREB tests
npm run test:creb

# Run only PubChem tests
npm run test:pubchem

Interactive Demos

Web-based Demos

Node.js Demos

# Enhanced Phase 2 demonstration
node demos/enhanced-demo.js

# Run TypeScript examples
npx ts-node examples/enhanced-usage.ts

Test Coverage

  • 57 tests covering all functionality
  • Enhanced classes with comprehensive test suites
  • Error handling and edge case validation
  • PubChem integration with graceful fallback testing
  • Browser compatibility testing

Demo Features

  1. Interactive Web Interface - Real-time calculations with instant feedback
  2. Enhanced Node.js Demo - Showcase of Phase 2 PubChem integration
  3. Automated Test Runner - Comprehensive validation of all features
  4. TypeScript Examples - Complete code examples with type safety
  5. Error Handling Demo - Graceful degradation when dependencies unavailable

Connect & Contribute

👨‍💻 Author: Loganathane Virassamy
🍴 Fork this project: GitHub Repository
Like this project? Give it a star on GitHub!

License

This project is licensed under the AGPL-3.0 License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Acknowledgments

Based on the original CREB Python project by LastChemist.