CREB-JS Documentation

Advanced Chemical Reaction Equation Balancer with PubChem Integration

๐Ÿงช What is CREB-JS?

CREB-JS is a comprehensive JavaScript library that revolutionizes chemical equation balancing and stoichiometric calculations. Built with modern TypeScript, it combines robust equation parsing algorithms with real-world chemical data from the PubChem database to provide accurate, validated chemical computations.

Whether you're a student learning chemistry, a researcher performing calculations, or a developer building chemical informatics applications, CREB-JS provides the tools you need with a simple, intuitive API.

๐Ÿš€ Quick Start

Get started with CREB-JS in just a few lines of code:

// Install the package npm install creb-js // Basic equation balancing import { ChemicalEquationBalancer } from 'creb-js'; const balancer = new ChemicalEquationBalancer(); const result = balancer.balance('H2 + O2 = H2O'); console.log(result); // "2 H2 + O2 = 2 H2O"
// Enhanced features with PubChem integration import { Compound } from 'creb-pubchem-js'; import { EnhancedStoichiometry } from 'creb-js'; // Search for compounds const aspirin = await Compound.fromName('aspirin'); console.log(aspirin.molecularFormula); // "C9H8O4" console.log(aspirin.molecularWeight); // 180.16 // Enhanced stoichiometry with real chemical data const enhanced = new EnhancedStoichiometry(); const analysis = await enhanced.calculateWithPubChem('C6H12O6 + O2 = CO2 + H2O');

โœจ Key Features

โš–๏ธ Smart Equation Balancing

Advanced algorithms automatically balance even complex chemical equations with robust error handling and validation.

๐Ÿงฎ Stoichiometric Calculations

Calculate molar relationships, limiting reagents, theoretical yields, and percent yields with precision.

๐Ÿ” PubChem Integration

Access real chemical data including molecular weights, formulas, properties, and structural information.

๐Ÿ†š Compound Comparison

Compare multiple compounds side-by-side with detailed property analysis and structural similarities.

โœ… Data Validation

Cross-reference calculated results with PubChem data to ensure accuracy and catch potential errors.

๐ŸŒ Universal Compatibility

Works in browsers, Node.js, and modern frameworks with TypeScript support and multiple output formats.

๐ŸŽฏ Use Cases

  • Educational Tools: Interactive chemistry learning platforms and homework helpers
  • Research Applications: Laboratory calculations and chemical analysis workflows
  • Industrial Software: Chemical process optimization and quality control systems
  • Web Applications: Chemistry calculators and molecular property databases
  • Academic Research: Computational chemistry and cheminformatics projects

๐Ÿ“š Documentation Structure

This documentation is organized into several sections to help you get the most out of CREB-JS:

  • Getting Started: Installation, setup, and basic usage patterns
  • Balancing Equations: Comprehensive guide to equation balancing features
  • Stoichiometry: Advanced calculations and molar relationships
  • PubChem Integration: Accessing and using real chemical data
  • API Reference: Complete method documentation and parameters
  • Examples: Practical code samples and common patterns

๐Ÿš€ Getting Started

Complete setup guide and first steps with CREB-JS

๐Ÿ“ฆ Installation

CREB-JS is distributed as npm packages. Choose the installation method that works best for your project:

1

Install Core Package

For basic equation balancing and stoichiometry calculations:

npm install creb-js
2

Add PubChem Integration (Optional)

For enhanced features with real chemical data:

npm install creb-pubchem-js
3

Browser Usage

For direct browser usage, include the UMD builds:

<script src="path/to/creb-js/dist/index.umd.js"></script> <script src="path/to/pubchem-js/dist/index.umd.js"></script>

โšก Quick Setup

Get up and running with CREB-JS in minutes:

// ES6 Modules (Node.js, modern bundlers) import { ChemicalEquationBalancer, EnhancedStoichiometry } from 'creb-js'; import { Compound } from 'creb-pubchem-js'; // CommonJS (Node.js) const { ChemicalEquationBalancer } = require('creb-js'); const { Compound } = require('creb-pubchem-js'); // Browser Global (UMD) const balancer = new window.CREB.ChemicalEquationBalancer(); const compound = new window.PubChemJS.Compound();

๐Ÿงช Your First Equation

Let's balance your first chemical equation with the interactive demo below:

โš—๏ธ Chemical Equation Balancer

Enter an unbalanced chemical equation and get the balanced version instantly.

Try examples: "H2 + O2 = H2O", "Fe + O2 = Fe2O3", "C3H8 + O2 = CO2 + H2O"
// This is what happens behind the scenes: import { ChemicalEquationBalancer } from 'creb-js'; const balancer = new ChemicalEquationBalancer(); const equation = 'Al + CuSO4 = Al2(SO4)3 + Cu'; const result = balancer.balance(equation); console.log(result); // Output: "2 Al + 3 CuSO4 = Al2(SO4)3 + 3 Cu"

๐ŸŽ“ Learning Path

Follow this recommended learning path to master CREB-JS:

1๏ธโƒฃ Basic Balancing

Start with simple equation balancing to understand the core functionality and API.

โ†’ Learn Balancing

2๏ธโƒฃ Stoichiometry

Learn to calculate molar relationships, limiting reagents, and yields.

โ†’ Learn Stoichiometry

3๏ธโƒฃ PubChem Data

Enhance your calculations with real chemical data from PubChem.

โ†’ Learn PubChem

4๏ธโƒฃ Advanced Features

Explore compound comparison, validation, and enhanced calculations.

โ†’ Advanced Features

๐Ÿ”ง Configuration

CREB-JS works out of the box with sensible defaults, but you can customize its behavior:

// Custom configuration example const balancer = new ChemicalEquationBalancer({ strictMode: true, // Stricter parsing rules allowPartialBalancing: false, // Require complete balancing maxIterations: 1000, // Maximum balancing attempts timeout: 10000 // Timeout in milliseconds }); // PubChem configuration const compound = new Compound({ apiKey: 'your-api-key', // Optional API key for higher rate limits timeout: 15000, // Request timeout retryAttempts: 3 // Number of retry attempts });

โ“ Need Help?

If you encounter any issues or have questions:

Balancing equations

Advanced equation balancing features

CREB-JS uses matrix algebra to solve systems of linear equations, ensuring accurate balancing of even complex chemical equations.

โš–๏ธ Advanced Equation Balancing

Try complex equations with multiple reactants and products:

How it works

The balancing algorithm:

  1. Parses the chemical equation to extract reactants and products
  2. Creates a matrix of element coefficients
  3. Solves the system using Gaussian elimination
  4. Returns the smallest integer coefficients

Stoichiometry

Calculate molar relationships and conversions

Perform stoichiometric calculations to determine the quantities of reactants and products in chemical reactions.

๐Ÿ“Š Stoichiometric Calculator

Calculate molar relationships from a balanced equation:

โš–๏ธ Molar Weight Calculator

Calculate the molar weight of any chemical formula:

๐Ÿงช Enhanced Chemical Intelligence

Advanced equation balancing with real-world compound data from PubChem

๐ŸŒŸ PubChem-Enhanced Balancing

Balance equations and get comprehensive compound information including molecular weights, IUPAC names, and validation from the authoritative PubChem database.

Enhanced Balancing Demo

๐Ÿ’ก Example Equations

Try these common chemical reactions to see enhanced balancing in action:

Acid-Base Neutralization

Sulfuric acid + Sodium hydroxide

Glucose Combustion

Cellular respiration reaction

Limestone Dissolution

Calcium carbonate + Hydrochloric acid

Iron Oxidation

Rust formation reaction

Ammonia Reaction

Ammonium chloride formation

Methane Combustion

Natural gas burning

๐Ÿ“Š Enhanced Intelligence Features

๐ŸŽฏ Real Molecular Weights

Get precise molecular weights from PubChem instead of calculated approximations.

๐Ÿท๏ธ IUPAC Names

See standardized chemical names alongside molecular formulas for better understanding.

โœ… Mass Balance Validation

Automatic verification that mass is conserved using real molecular weight data.

๐Ÿ” Compound Validation

Verify that all compounds in your equation exist and are correctly identified.

๐Ÿ’ป Enhanced Intelligence API

Access enhanced chemical intelligence in your applications:

import { EnhancedChemicalEquationBalancer } from 'creb-js'; const balancer = new EnhancedChemicalEquationBalancer(); const result = await balancer.balanceWithPubChemData("H2SO4 + NaOH = Na2SO4 + H2O"); console.log(result.coefficients); // [1, 2, 1, 2] console.log(result.compoundData.H2SO4.iupacName); // "sulfuric acid" console.log(result.compoundData.H2SO4.molarWeight); // 98.08 g/mol (from PubChem) console.log(result.validation.massBalanced); // true

๐Ÿท๏ธ Compound Name Resolution

Balance equations using common chemical names instead of formulas

๐ŸŒŸ Balance by Common Names

Enter equations using everyday chemical names like "water", "sulfuric acid", or "sodium hydroxide". CREB-JS will automatically resolve these names to their chemical formulas using PubChem and then balance the equation.

Name Resolution Demo

๐Ÿ’ก Common Name Examples

Try these equations using common chemical names:

Acid-Base Reaction

Using common acid/base names

Gas Absorption

HCl gas + ammonia reaction

Cellular Respiration

Using biochemical names

Natural Gas Combustion

Common fuel burning

Limestone Reaction

Geological chemistry

Alcohol Combustion

Ethyl alcohol burning

๐Ÿ“Š Name Resolution Features

๐Ÿง  Intelligent Parsing

Automatically identifies and separates compound names from the equation structure.

๐Ÿท๏ธ Name Standardization

Handles variations like "sulfuric acid" vs "sulphuric acid" automatically.

๐Ÿ” PubChem Resolution

Resolves names to chemical formulas using PubChem's comprehensive database.

๐Ÿ”— Name Mapping

Maintains mapping between original names and resolved formulas for transparency.

๐Ÿ’ป Name Resolution API

Use name resolution in your applications:

import { EnhancedChemicalEquationBalancer } from 'creb-js'; const balancer = new EnhancedChemicalEquationBalancer(); const result = await balancer.balanceByName( "sulfuric acid + sodium hydroxide = sodium sulfate + water" ); console.log(result.equation); // "H2O4S + 2 HNaO = Na2O4S + 2 H2O" // See how names were resolved for (const [formula, info] of Object.entries(result.compoundData)) { if (info.originalName) { console.log(`"${info.originalName}" โ†’ ${formula}`); } }

โš—๏ธ Enhanced Stoichiometry

Precise stoichiometric calculations using real molecular weights from PubChem

๐ŸŒŸ PubChem-Powered Calculations

Perform stoichiometric calculations with unprecedented accuracy using real molecular weights from the PubChem database. Compare calculated vs. real molecular weights and get precision assessments.

Enhanced Stoichiometry Demo

๐Ÿ’ก Example Calculations

Try these stoichiometry problems with enhanced accuracy:

Silver Chloride Precipitation

0.171 mol NaCl โ†’ ? g AgCl

Glucose Respiration

1.0 mol glucose โ†’ ? g COโ‚‚

Water Formation

2.0 mol Hโ‚‚ โ†’ ? g Hโ‚‚O

Limestone Dissolution

0.5 mol CaCOโ‚ƒ โ†’ ? g COโ‚‚

Iron Chloride Formation

1.5 mol Fe โ†’ ? g FeClโ‚ƒ

Methane Combustion

0.75 mol CHโ‚„ โ†’ ? g Hโ‚‚O

๐Ÿ“Š Enhanced Stoichiometry Features

๐ŸŽฏ Real Molecular Weights

Use precise molecular weights from PubChem instead of calculated approximations.

๐Ÿ“Š Accuracy Analysis

Compare calculated vs. real molecular weights and assess precision levels.

โœ… Mass Balance Validation

Verify conservation of mass using real molecular weight data.

๐Ÿ” Compound Validation

Ensure all compounds exist and are correctly identified before calculations.

๐Ÿ’ป Enhanced Stoichiometry API

Perform enhanced calculations in your applications:

import { EnhancedStoichiometry } from 'creb-js'; const stoich = new EnhancedStoichiometry(); await stoich.initializeWithValidation("2 NaCl + AgNO3 = AgCl + 2 NaNO3"); const result = await stoich.calculateFromMolesEnhanced("NaCl", 0.171); console.log(result.products.AgCl.grams); // 24.51 g (PubChem accuracy) console.log(result.pubchemMolarWeights.AgCl); // 143.32 g/mol (real weight) console.log(result.validation.warnings); // Precision analysis

โš ๏ธ Chemical Safety Information

Comprehensive safety warnings and hazard classifications for chemical reactions

๐Ÿ›ก๏ธ GHS Safety Integration

Get comprehensive safety information including GHS hazard classifications, signal words, and precautionary statements for all compounds in your chemical equations.

Safety Analysis Demo

๐Ÿ’ก Example Safety Analyses

See safety information for these common chemical reactions:

Strong Acid + Base

High hazard corrosive reaction

Acid + Ammonia

Respiratory and corrosion hazards

Glucose Combustion

Relatively safe organic reaction

Methane Combustion

Flammable gas hazards

Limestone + Acid

Acid handling precautions

Iron Oxidation

Minimal safety concerns

๐Ÿ“Š Safety Information Features

๐Ÿ”ด GHS Classifications

Standard H-codes (H314, H290, etc.) for consistent hazard identification.

โš ๏ธ Severity Levels

Color-coded warnings: ๐Ÿ”ด Extreme, ๐ŸŸ  High, ๐ŸŸก Medium, ๐ŸŸข Low hazards.

๐Ÿ›ก๏ธ Precautionary Statements

Specific safety recommendations for handling each chemical.

๐Ÿ“‹ Signal Words

Standard "Danger" or "Warning" classifications per GHS guidelines.

๐ŸŽจ Safety Color Code

๐Ÿ”ด

Extreme Hazard

Fatal, severe burns, extreme toxicity

๐ŸŸ 

High Hazard

Serious injury, corrosive, harmful

๐ŸŸก

Medium Hazard

Irritant, mild toxicity, caution required

๐ŸŸข

Low Hazard

Minimal risk, general precautions

๐Ÿ’ป Safety Information API

Integrate safety analysis into your applications:

import { EnhancedChemicalEquationBalancer } from 'creb-js'; const balancer = new EnhancedChemicalEquationBalancer(); const result = await balancer.balanceWithSafety("H2SO4 + NaOH = Na2SO4 + H2O"); result.safetyWarnings.forEach(warning => { console.log(`โš ๏ธ ${warning.compound}: ${warning.hazard}`); console.log(` Severity: ${warning.severity}`); console.log(` GHS: ${warning.ghsClassification}`); }); // Access detailed safety data const h2so4Safety = result.compoundData.H2SO4.safetyInfo; console.log(`Signal Word: ${h2so4Safety.signalWord}`); // "Danger"

Enhanced Chemical Equation Balancer with PubChem Validation

Enhanced Stoichiometry with PubChem Data

Compound Comparison

});

โ„น๏ธ About CREB-JS

Chemical Reaction Equation Balancer with Advanced Features

Project Overview

CREB-JS is a comprehensive chemical equation balancer and stoichiometry calculator, enhanced with real chemical data from the PubChem database. This project combines robust equation balancing algorithms with modern web technologies to provide an intuitive chemical computation toolkit.

โš—๏ธ

Equation Balancing

Advanced algorithms to balance complex chemical equations automatically with detailed error handling and validation.

๐Ÿงฎ

Stoichiometry

Calculate molar relationships, convert between units, and perform comprehensive stoichiometric analysis.

๐Ÿงฌ

PubChem Integration

Access real chemical data including molecular weights, formulas, SMILES, and comprehensive compound information.

๐Ÿ”

Compound Search

Search compounds by name, CID, SMILES, or molecular formula with intelligent matching and suggestions.

๐Ÿ“Š

Analysis Tools

Compare compounds, analyze molecular properties, and perform enhanced stoichiometric calculations.

๐ŸŒ

Modern Web Stack

Built with TypeScript, modern ES modules, comprehensive testing, and responsive design principles.

Technical Stack

Core: TypeScript, Rollup, Jest

Integration: PubChem REST API, Modern HTTP Client

Build: Multiple output formats (CJS, ESM, UMD)

Testing: Comprehensive unit and integration tests

๐Ÿ“š API Documentation

Complete reference for CREB-JS APIs and methods

๐Ÿงช ChemicalEquationBalancer

The core class for balancing chemical equations with advanced parsing and validation.

constructor(options?: BalancerOptions)
Description

Creates a new ChemicalEquationBalancer instance with optional configuration.

Parameters
options (optional) - Configuration object with the following properties:
โ€ข strictMode: boolean - Enable stricter parsing (default: false)
โ€ข maxIterations: number - Maximum balancing attempts (default: 100)
โ€ข timeout: number - Timeout in milliseconds (default: 5000)
Example
const balancer = new ChemicalEquationBalancer({ strictMode: true, maxIterations: 200, timeout: 10000 });
balance(equation: string): string
Description

Balances a chemical equation and returns the balanced equation as a string.

Parameters
equation - The unbalanced chemical equation string
Returns

Balanced chemical equation string with coefficients

Example
const result = balancer.balance('H2 + O2 = H2O'); // Returns: "2 H2 + O2 = 2 H2O"
calculateStoichiometry(equation: string, compound: string, amount: number): StoichiometryResult
Description

Calculates stoichiometric relationships for a given compound and amount.

Parameters
equation - Balanced chemical equation
compound - Target compound formula
amount - Amount in moles
Returns

Object containing molar relationships for all compounds in the equation

Example
const stoich = balancer.calculateStoichiometry('2 H2 + O2 = 2 H2O', 'H2', 4); // Returns molar amounts for all compounds based on 4 moles of H2
async balanceByName(equation: string): Promise<EnhancedBalanceResult> โœจ NEW!
Description

Balance chemical equations using compound names instead of formulas. Automatically resolves compound names to chemical formulas using PubChem database and provides enhanced results with compound information.

Parameters
equation - Chemical equation with compound names (e.g., "water + sodium = sodium hydroxide + hydrogen")
Returns

Promise resolving to enhanced balance result with compound data, safety information, and balance details

Example
const result = await balancer.balanceByName('water + sodium = sodium hydroxide + hydrogen'); console.log(result.balanced); // Balanced equation with formulas console.log(result.compounds); // Array of compound objects with PubChem data
async balanceWithSafety(equation: string): Promise<SafetyEnhancedResult> โœจ NEW!
Description

Balance chemical equations and include comprehensive safety information for all compounds. Provides GHS hazard classifications, safety warnings, and handling recommendations.

Parameters
equation - Chemical equation string with compound formulas or names
Returns

Promise resolving to result with balanced equation, compound data, and detailed safety information

Example
const result = await balancer.balanceWithSafety('H2SO4 + NaOH = Na2SO4 + H2O'); console.log(result.balanced); // Balanced equation console.log(result.safetyInfo); // Safety classifications and warnings result.safetyInfo.hazards.forEach(h => console.log(h.statement));

๐Ÿ”ฌ Compound (PubChem Integration)

Access PubChem database for real chemical compound data and properties.

static async fromCid(cid: number): Promise<Compound>
Description

Retrieve a compound by its PubChem Compound ID (CID).

Parameters
cid - PubChem Compound ID (numeric)
Returns

Promise resolving to a single Compound instance

Example
const water = await Compound.fromCid(962); const glucose = await Compound.fromCid(5793);
static async fromName(name: string): Promise<Compound[]>
Description

Search for compounds by common or IUPAC name. Returns array of all matching compounds.

Parameters
name - Common name, IUPAC name, or synonym of the compound
Returns

Promise resolving to array of Compound instances

Example
const aspirinResults = await Compound.fromName('aspirin'); const aspirin = aspirinResults[0]; // Get first result console.log(`Found ${aspirinResults.length} compounds`);
static async getByName(name: string): Promise<Compound | null>
Description

Convenience method to get the first compound matching a name, or null if not found.

Parameters
name - Common name, IUPAC name, or synonym of the compound
Returns

Promise resolving to a single Compound instance or null

Example
const aspirin = await Compound.getByName('aspirin'); const caffeine = await Compound.getByName('caffeine');
static async fromSmiles(smiles: string): Promise<Compound[]>
Description

Search for compounds using SMILES notation. Returns array of all matching compounds.

Parameters
smiles - SMILES string representation of the molecule
Returns

Promise resolving to array of Compound instances

Example
const benzeneResults = await Compound.fromSmiles('c1ccccc1'); const ethanolResults = await Compound.fromSmiles('CCO');
static async getBySmiles(smiles: string): Promise<Compound | null>
Description

Convenience method to get the first compound matching a SMILES string.

Parameters
smiles - SMILES string representation of the molecule
Returns

Promise resolving to a single Compound instance or null

Example
const benzene = await Compound.getBySmiles('c1ccccc1'); const ethanol = await Compound.getBySmiles('CCO');
static async fromFormula(formula: string): Promise<Compound[]> โœจ NEW!
Description

Search for compounds by molecular formula. Returns array of all compounds with matching formula (up to 100 results).

Parameters
formula - Molecular formula (e.g., "H2O", "C6H12O6", "C9H8O4")
Returns

Promise resolving to array of Compound instances

Example
const waterCompounds = await Compound.fromFormula('H2O'); const glucoseIsomers = await Compound.fromFormula('C6H12O6'); console.log(`Found ${glucoseIsomers.length} compounds with formula C6H12O6`);
static async getByFormula(formula: string): Promise<Compound | null> โœจ NEW!
Description

Convenience method to get the first compound matching a molecular formula.

Parameters
formula - Molecular formula (e.g., "H2O", "C6H12O6", "C9H8O4")
Returns

Promise resolving to a single Compound instance or null

Example
const water = await Compound.getByFormula('H2O'); const glucose = await Compound.getByFormula('C6H12O6'); const aspirin = await Compound.getByFormula('C9H8O4');

๐Ÿ“Š Compound Properties

Available properties on Compound instances retrieved from PubChem:

Basic Properties

  • cid - PubChem Compound ID
  • name - Primary compound name
  • molecularFormula - Chemical formula
  • molecularWeight - Molecular weight (g/mol)

Structural Data

  • smiles - SMILES notation
  • inchi - InChI identifier
  • inchiKey - InChI Key
  • iupacName - IUPAC systematic name

Physical Properties

  • meltingPoint - Melting point (ยฐC)
  • boilingPoint - Boiling point (ยฐC)
  • density - Density (g/cmยณ)
  • solubility - Water solubility

Chemical Properties

  • charge - Formal charge
  • complexity - Structural complexity
  • heavyAtomCount - Number of heavy atoms
  • synonyms - Array of name synonyms

โš—๏ธ EnhancedStoichiometry

Advanced stoichiometric calculations with PubChem validation and enhanced features.

async calculateWithPubChem(equation: string): Promise<EnhancedResult>
Description

Performs equation balancing with PubChem validation and enhanced stoichiometric analysis.

Parameters
equation - Chemical equation to balance and analyze
Returns

Promise resolving to an object containing:

  • balancedEquation - The balanced equation
  • validation - PubChem validation results
  • compounds - Array of PubChem compound data
  • massBalance - Mass balance verification
  • stoichiometry - Detailed stoichiometric relationships
Example
const enhanced = new EnhancedStoichiometry(); const result = await enhanced.calculateWithPubChem('C6H12O6 + O2 = CO2 + H2O'); console.log(result.balancedEquation); // Balanced equation console.log(result.validation.isValid); // PubChem validation status console.log(result.compounds); // Compound data array
async calculateReagentQuantities(equation: string, targetCompound: string, desiredAmount: number, unit?: string): Promise<ReagentCalculationResult> โœจ NEW!
Description

Calculate required reagent quantities for a chemical reaction based on desired product amount. Includes molecular weight data from PubChem for accurate mass calculations.

Parameters
equation - Chemical equation string
targetCompound - Formula of the target product compound
desiredAmount - Desired amount of target compound
unit - Unit for calculations ('moles' or 'grams', default: 'moles')
Returns

Promise resolving to detailed reagent quantity calculations with molecular data

Example
const enhanced = new EnhancedStoichiometry(); const result = await enhanced.calculateReagentQuantities( 'C6H12O6 + 6O2 = 6CO2 + 6H2O', 'CO2', 10, 'grams' ); console.log(result.reagents); // Required amounts of all reagents
async getReactionEfficiency(equation: string, actualYields: Record<string, number>): Promise<EfficiencyAnalysis> โœจ NEW!
Description

Analyze reaction efficiency by comparing theoretical vs actual yields for products. Provides detailed efficiency metrics and identifies limiting reagents.

Parameters
equation - Balanced chemical equation
actualYields - Object mapping compound formulas to their actual yields
Returns

Promise resolving to comprehensive efficiency analysis with yield percentages and recommendations

Example
const enhanced = new EnhancedStoichiometry(); const efficiency = await enhanced.getReactionEfficiency( '2H2 + O2 = 2H2O', { 'H2O': 1.8 } // Actual yield: 1.8 moles of water ); console.log(efficiency.yieldPercentage); // Efficiency percentage console.log(efficiency.limitingReagent); // Identified limiting reagent

๐Ÿ”ง Error Handling

CREB-JS provides comprehensive error handling for robust applications:

try { const result = balancer.balance('invalid equation'); } catch (error) { if (error instanceof BalancingError) { console.log('Could not balance equation:', error.message); } else if (error instanceof ParseError) { console.log('Could not parse equation:', error.message); } } // Async error handling for PubChem operations try { const compound = await Compound.fromName('nonexistent compound'); } catch (error) { if (error instanceof CompoundNotFoundError) { console.log('Compound not found in PubChem'); } else if (error instanceof NetworkError) { console.log('Network error accessing PubChem'); } }

๐Ÿ“– Type Definitions

CREB-JS is fully typed with TypeScript. Key interfaces include:

interface StoichiometryResult { compound: string; coefficient: number; moles: number; mass: number; percentage: number; } interface BalancerOptions { strictMode?: boolean; maxIterations?: number; timeout?: number; } interface EnhancedResult { balancedEquation: string; validation: ValidationResult; compounds: CompoundData[]; massBalance: MassBalanceResult; stoichiometry: StoichiometryResult[]; } // Enhanced Features Types โœจ NEW! interface EnhancedBalanceResult { balanced: string; compounds: CompoundInfo[]; intelligence: ChemicalIntelligence; validation: ValidationResult; } interface SafetyEnhancedResult { balanced: string; compounds: CompoundInfo[]; safetyInfo: SafetyInformation; validation: ValidationResult; } interface SafetyInformation { overallRisk: 'LOW' | 'MODERATE' | 'HIGH' | 'EXTREME'; hazards: GHSHazard[]; warnings: string[]; recommendations: string[]; personalProtection: string[]; } interface GHSHazard { code: string; // e.g., "H301" category: string; // e.g., "Acute toxicity" statement: string; // e.g., "Toxic if swallowed" severity: 'LOW' | 'MODERATE' | 'HIGH' | 'EXTREME'; } interface ReagentCalculationResult { equation: string; target: CompoundInfo; reagents: Record<string, ReagentQuantity>; massBalance: MassBalanceData; } interface EfficiencyAnalysis { yieldPercentage: number; limitingReagent: string; theoreticalYields: Record<string, number>; actualYields: Record<string, number>; efficiency: Record<string, number>; }

๐Ÿ’ก Code Examples

Practical examples and real-world usage patterns

๐Ÿ”ค Basic Equation Balancing

Start with simple equation balancing for common chemical reactions:

import { ChemicalEquationBalancer } from 'creb-js'; const balancer = new ChemicalEquationBalancer(); // Simple synthesis reactions console.log(balancer.balance('H2 + O2 = H2O')); // Output: "2 H2 + O2 = 2 H2O" console.log(balancer.balance('Fe + O2 = Fe2O3')); // Output: "4 Fe + 3 O2 = 2 Fe2O3" // Combustion reactions console.log(balancer.balance('C3H8 + O2 = CO2 + H2O')); // Output: "C3H8 + 5 O2 = 3 CO2 + 4 H2O" console.log(balancer.balance('C6H12O6 + O2 = CO2 + H2O')); // Output: "C6H12O6 + 6 O2 = 6 CO2 + 6 H2O"

๐Ÿงฎ Stoichiometric Calculations

Calculate molar relationships and quantities in chemical reactions:

// Calculate stoichiometry for a balanced equation const equation = '2 H2 + O2 = 2 H2O'; const stoichResult = balancer.calculateStoichiometry(equation, 'H2', 4); console.log(`Starting with 4 moles of H2:`); console.log(`O2 needed: ${stoichResult.O2.moles} moles`); console.log(`H2O produced: ${stoichResult.H2O.moles} moles`); // Mass calculations const massResult = balancer.calculateStoichiometry(equation, 'H2', 2, 'mass'); console.log(`H2 mass: ${massResult.H2.mass} g`); console.log(`O2 mass needed: ${massResult.O2.mass} g`); console.log(`H2O mass produced: ${massResult.H2O.mass} g`);

๐Ÿ”ฌ PubChem Integration

Access real chemical data from the PubChem database:

import { Compound } from 'creb-pubchem-js'; // Search compounds by different methods async function searchExamples() { // By common name const aspirin = await Compound.fromName('aspirin'); console.log(`Aspirin formula: ${aspirin.molecularFormula}`); // C9H8O4 console.log(`Molecular weight: ${aspirin.molecularWeight}`); // 180.16 // By PubChem CID const caffeine = await Compound.fromCID(2519); console.log(`Caffeine SMILES: ${caffeine.smiles}`); // By SMILES notation const ethanol = await Compound.fromSMILES('CCO'); console.log(`Ethanol IUPAC: ${ethanol.iupacName}`); // Access various properties console.log(`Solubility: ${aspirin.solubility}`); console.log(`Melting point: ${aspirin.meltingPoint}ยฐC`); console.log(`Synonyms: ${aspirin.synonyms.slice(0, 3).join(', ')}`); }

โš—๏ธ Enhanced Stoichiometry

Combine equation balancing with PubChem validation for accurate calculations:

import { EnhancedStoichiometry } from 'creb-js'; async function enhancedCalculations() { const enhanced = new EnhancedStoichiometry(); // Enhanced equation balancing with validation const result = await enhanced.calculateWithPubChem( 'C6H12O6 + O2 = CO2 + H2O' ); console.log('Balanced equation:', result.balancedEquation); console.log('Validation status:', result.validation.isValid); console.log('Mass balance check:', result.massBalance.isBalanced); // Access compound data result.compounds.forEach(compound => { console.log(`${compound.formula}: ${compound.name}`); console.log(` Molecular weight: ${compound.molecularWeight}`); console.log(` PubChem CID: ${compound.cid}`); }); // Detailed stoichiometric analysis console.log('Stoichiometric relationships:'); result.stoichiometry.forEach(relation => { console.log(` ${relation.compound}: ${relation.coefficient} moles`); }); }

๐Ÿ†š Compound Comparison

Compare multiple compounds side-by-side for research and analysis:

async function compareCompounds() { // Compare pain relievers const compounds = await Promise.all([ Compound.fromName('aspirin'), Compound.fromName('ibuprofen'), Compound.fromName('acetaminophen') ]); console.log('Pain Reliever Comparison:'); console.log('========================'); compounds.forEach(compound => { console.log(`\n${compound.name}:`); console.log(` Formula: ${compound.molecularFormula}`); console.log(` Weight: ${compound.molecularWeight} g/mol`); console.log(` Complexity: ${compound.complexity}`); console.log(` Heavy atoms: ${compound.heavyAtomCount}`); }); // Find compound with highest/lowest molecular weight const heaviest = compounds.reduce((prev, current) => prev.molecularWeight > current.molecularWeight ? prev : current ); console.log(`\nHeaviest compound: ${heaviest.name} (${heaviest.molecularWeight} g/mol)`); }

๐Ÿ”„ Batch Processing

Process multiple equations or compounds efficiently:

async function batchProcessing() { const balancer = new ChemicalEquationBalancer(); // Batch equation balancing const equations = [ 'H2 + O2 = H2O', 'CH4 + O2 = CO2 + H2O', 'Fe + HCl = FeCl2 + H2', 'CaCO3 = CaO + CO2' ]; const balancedEquations = equations.map(eq => ({ original: eq, balanced: balancer.balance(eq) })); console.log('Batch Balancing Results:'); balancedEquations.forEach(result => { console.log(`${result.original} โ†’ ${result.balanced}`); }); // Batch compound lookup const compoundNames = ['water', 'glucose', 'sodium chloride', 'caffeine']; const compoundData = await Promise.all( compoundNames.map(async name => { try { const compound = await Compound.fromName(name); return { name: compound.name, formula: compound.molecularFormula, weight: compound.molecularWeight, cid: compound.cid }; } catch (error) { return { name, error: error.message }; } }) ); console.log('\nBatch Compound Lookup:'); compoundData.forEach(data => { if (data.error) { console.log(`${data.name}: Error - ${data.error}`); } else { console.log(`${data.name}: ${data.formula} (MW: ${data.weight}, CID: ${data.cid})`); } }); }

๐Ÿ› ๏ธ Error Handling & Validation

Robust error handling for production applications:

import { BalancingError, ParseError, CompoundNotFoundError } from 'creb-js'; async function robustChemicalCalculations() { const balancer = new ChemicalEquationBalancer(); // Safe equation balancing function safeBalance(equation) { try { const result = balancer.balance(equation); return { success: true, result }; } catch (error) { if (error instanceof BalancingError) { return { success: false, error: 'Could not balance equation', details: error.message }; } else if (error instanceof ParseError) { return { success: false, error: 'Invalid equation format', details: error.message }; } else { return { success: false, error: 'Unexpected error', details: error.message }; } } } // Safe compound lookup async function safeCompoundLookup(identifier, method = 'name') { try { let compound; switch (method) { case 'name': compound = await Compound.fromName(identifier); break; case 'cid': compound = await Compound.fromCID(identifier); break; case 'smiles': compound = await Compound.fromSMILES(identifier); break; default: throw new Error('Invalid lookup method'); } return { success: true, compound }; } catch (error) { if (error instanceof CompoundNotFoundError) { return { success: false, error: 'Compound not found in PubChem' }; } else { return { success: false, error: 'Lookup failed', details: error.message }; } } } // Usage examples const balanceResult = safeBalance('H2 + O2 = H2O'); if (balanceResult.success) { console.log('Balanced:', balanceResult.result); } else { console.error('Error:', balanceResult.error); } const compoundResult = await safeCompoundLookup('aspirin'); if (compoundResult.success) { console.log('Found:', compoundResult.compound.name); } else { console.error('Error:', compoundResult.error); } }

๐ŸŒ Browser Integration

Using CREB-JS in web applications with modern frameworks:

// React component example import React, { useState, useEffect } from 'react'; import { ChemicalEquationBalancer } from 'creb-js'; import { Compound } from 'creb-pubchem-js'; function ChemicalCalculator() { const [equation, setEquation] = useState(''); const [result, setResult] = useState(''); const [balancer] = useState(() => new ChemicalEquationBalancer()); const handleBalance = async () => { try { const balanced = balancer.balance(equation); setResult(balanced); } catch (error) { setResult(`Error: ${error.message}`); } }; return ( <div> <input value={equation} onChange={(e) => setEquation(e.target.value)} placeholder="Enter chemical equation" /> <button onClick={handleBalance}>Balance</button> <div>Result: {result}</div> </div> ); } // Vue.js component example export default { data() { return { compoundName: '', compoundData: null, loading: false }; }, methods: { async searchCompound() { this.loading = true; try { this.compoundData = await Compound.fromName(this.compoundName); } catch (error) { console.error('Search failed:', error); this.compoundData = null; } finally { this.loading = false; } } } };

โš–๏ธ Compound Comparison

Compare chemical compounds side by side

Compare Compounds

๐Ÿ“– User Guide

Complete guide to using CREB-JS effectively

Getting Started

CREB-JS provides comprehensive chemical equation balancing and analysis. Start with basic equation balancing and progress to advanced PubChem integration.

  1. Install the package: npm install creb-js
  2. Import the balancer: import { ChemicalEquationBalancer } from 'creb-js'
  3. Create an instance and balance equations

Best Practices

  • Use standard chemical notation (H2O, CO2, etc.)
  • Include states when relevant (g), (l), (s), (aq)
  • Leverage PubChem integration for accurate molecular data
  • Cache compound data when performing multiple calculations