Constantinople Constant Expression Evaluator

4.0.1 · active · verified Sun Apr 19

Constantinople is a JavaScript utility package, currently at stable version 4.0.1, designed to determine if a given JavaScript expression evaluates to a constant. It parses the expression into an Abstract Syntax Tree (AST) using Babylon (now part of Babel's parser) to analyze its predictability. The library prioritizes safety, conservatively returning `false` if there's any uncertainty, ensuring reliability for build tools and static analysis where incorrect constant detection could cause issues. It also provides a `toConstant` function to safely evaluate expressions identified as constant, throwing an error if the expression is not constant. The package ships with TypeScript type definitions, enhancing developer experience for TypeScript users.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `isConstant` to check if an expression is constant and `toConstant` to evaluate its value, including handling non-constant expressions and custom constant contexts.

import isConstant from 'constantinople';

const expression1 = '"foo" + 5';
const expression2 = 'Math.floor(10.5)';
const expression3 = 'Date.now()'; // Example of a non-constant

// Check and evaluate a simple constant string concatenation
if (isConstant(expression1)) {
  console.log(`'${expression1}' is constant.`);
  try {
    const result = isConstant.toConstant(expression1);
    console.log(`Value: ${result}`); // Expected: "foo5"
  } catch (error: any) {
    console.error(`Error evaluating '${expression1}':`, error.message);
  }
} else {
  console.log(`'${expression1}' is not constant.`);
}

console.log('---\n');

// Check and evaluate with provided constants (e.g., Math object)
// WARNING: Providing global objects like Math might lead to unexpected behavior if they contain non-constant functions like Math.random
if (isConstant(expression2, { Math: Math })) {
  console.log(`'${expression2}' is constant with Math context.`);
  try {
    const result = isConstant.toConstant(expression2, { Math: Math });
    console.log(`Value: ${result}`); // Expected: 10
  } catch (error: any) {
    console.error(`Error evaluating '${expression2}':`, error.message);
  }
} else {
  console.log(`'${expression2}' is not constant with Math context.`);
}

console.log('---\n');

// Demonstrate a non-constant expression
if (isConstant(expression3)) {
  console.log(`'${expression3}' is constant.`);
} else {
  console.log(`'${expression3}' is not constant.`);
  try {
    isConstant.toConstant(expression3); // This will throw an error
  } catch (error: any) {
    console.error(`Attempting to evaluate non-constant '${expression3}' throws: ${error.message}`);
  }
}

view raw JSON →