GLINR Studio LogoTypeWeaver

JavaScript ↔ Python Cross-Reference

Complete API parity reference between JavaScript and Python implementations

Edit on GitHub

Complete cross-platform API reference showing exact method correspondence between JavaScript and Python implementations. All methods provide identical functionality with language-appropriate naming conventions.

✅ 100% Feature Parity

Every JavaScript method has an equivalent Python implementation with identical functionality, parameters, and return values.

Core Functions API

Primary Detection Methods

JavaScript MethodPython MethodDescriptionDocumentation Links
checkProfanity()check_profanity()Main profanity detection with full configuration supportJS Docs | Python Docs
isWordProfane()is_word_profane()Quick boolean check for single wordsJS Docs | Python Docs
checkProfanityAsync()check_profanity_async()Promise-based async profanity detectionJS Docs | Python Docs
validateText()validate_text()Comprehensive text validation with suggestionsJS Docs | Python Docs
getLanguageInfo()get_language_info()Get supported language capabilities and informationJS Docs | Python Docs

Filter Class API

Object-Oriented Interface

JavaScript MethodPython MethodDescriptionDocumentation Links
new Filter(config)Filter(config)Filter class constructor with persistent configurationJS Docs | Python Docs
filter.check(text)filter.check(text)Check profanity using instance configurationJS Docs | Python Docs
filter.checkWithMinSeverity()filter.check_with_min_severity()Filter by severity threshold (MILD/MODERATE/SEVERE)JS Docs | Python Docs
filter.isProfane(word)filter.is_profane(word)Quick word check using instance configurationJS Docs | Python Docs
filter.updateConfig()filter.update_config()Update instance configuration dynamicallyJS Docs | Python Docs
filter.getConfig()filter.get_config()Get current instance configurationJS Docs | Python Docs
filter.resetConfig()filter.reset_config()Reset configuration to defaultsJS Docs | Python Docs
filter.clearCache()filter.clear_cache()Clear internal result cacheJS Docs | Python Docs
filter.getCacheStats()filter.get_cache_stats()Get cache performance statisticsJS Docs | Python Docs

Batch Processing API

Multiple Text Processing

JavaScript MethodPython MethodDescriptionDocumentation Links
checkMultiple()check_multiple()Process multiple texts efficiently with shared configurationJS Docs | Python Docs
validateMultiple()validate_multiple()Validate multiple texts with comprehensive resultsJS Docs | Python Docs
processBatch()process_batch()High-performance batch processing with streaming supportJS Docs | Python Docs

React Integration API

React Hook (JavaScript Only)

JavaScript MethodPython EquivalentDescriptionDocumentation Links
useProfanityChecker()N/A - JavaScript OnlyReact hook for profanity checking with state managementReact Hook Docs
hook.checkText()Use Flask/Django patternsCheck text and update hook stateReact Hook Docs
hook.checkTextAsync()Use async Flask routesAsync text checking with loading statesReact Hook Docs
hook.reset()Manage state manuallyReset hook state to initial valuesReact Hook Docs

React Integration: Python doesn't have React hooks, but equivalent functionality can be achieved using Flask/Django with async routes and proper state management on the frontend.

Configuration Options

Complete Configuration Parity

JavaScript ConfigPython ConfigDescriptionDefault Values
languages: string[]languages: List[str]Specific languages to check for profanity['english']
allLanguages: booleanall_languages: boolCheck all 23 supported languagesfalse / False
enableContextAware: booleanenable_context_aware: boolEnable NLP-based context analysisfalse / False
confidenceThreshold: numberconfidence_threshold: floatContext confidence threshold (0.0-1.0)0.7
contextWindow: numbercontext_window: intNumber of words to analyze for context3
caseSensitive: booleancase_sensitive: boolEnable case-sensitive matchingfalse / False
wordBoundaries: booleanword_boundaries: boolEnforce word boundaries for exact matchingtrue / True
allowObfuscatedMatch: booleanallow_obfuscated_match: boolDetect disguised profanity (sh1t, f*ck)false / False
fuzzyMatching: booleanfuzzy_matching: boolEnable fuzzy matching for similar wordstrue / True
fuzzyTolerance: numberfuzzy_tolerance: floatCharacter similarity threshold (0.0-1.0)0.8
autoReplace: booleanauto_replace: boolAutomatically return text with profanity replacedfalse / False
replaceChar: stringreplace_char: strCharacter to use for replacement'●'
preserveLength: booleanpreserve_length: boolPreserve original word length in replacementstrue / True
severityFilter: stringseverity_filter: strMinimum severity to flag (MILD/MODERATE/SEVERE)'MODERATE'
enableCaching: booleanenable_caching: boolEnable result caching for performancefalse / False
cacheSize: numbercache_size: intMaximum number of cached results1000

Return Value Structures

Cross-Platform Return Types

JavaScript Return Types
interface ProfanityCheckResult {
  containsProfanity: boolean;
  profaneWords: string[];
  processedText?: string;
  filteredWords: string[];
  autoReplaced?: string;
  severityMap?: Record<string, SeverityLevel>;
  matches?: Match[];
  contextScore?: number;
}

interface ValidationResult {
  isValid: boolean;
  errors: string[];
  suggestions: string[];
  confidence: number;
  alternatives: Record<string, string[]>;
}

interface CacheStats {
  hits: number;
  misses: number;
  hitRate: number;
  size: number;
  maxSize: number;
}
Python Return Types
class ProfanityCheckResult:
    contains_profanity: bool
    profane_words: List[str]
    processed_text: Optional[str]
    filtered_words: List[str]
    auto_replaced: Optional[str]
    severity_map: Optional[Dict[str, SeverityLevel]]
    matches: Optional[List[Match]]
    context_score: Optional[float]

class ValidationResult:
    is_valid: bool
    errors: List[str]
    suggestions: List[str]
    confidence: float
    alternatives: Dict[str, List[str]]

class CacheStats:
    hits: int
    misses: int
    hit_rate: float
    size: int
    max_size: int

Usage Examples Comparison

Side-by-Side Implementation Examples

JavaScript Usage Examples
import { checkProfanity, Filter } from 'glin-profanity';

// Basic usage
const result = checkProfanity("This is damn good!", {
  languages: ['english'],
  enableContextAware: true,
  confidenceThreshold: 0.7
});

// Filter class usage
const filter = new Filter({
  languages: ['english', 'spanish'],
  enableContextAware: true,
  autoReplace: true,
  replaceChar: '●'
});

const processedResult = filter.check("Text to analyze");

// Batch processing
const batchResults = filter.checkMultiple([
  "First text to check",
  "Second text to analyze",
  "Third piece of content"
]);

// Configuration updates
filter.updateConfig({
  confidenceThreshold: 0.8,
  severityFilter: 'MODERATE'
});

// Cache management
const stats = filter.getCacheStats();
filter.clearCache();
Python Usage Examples
from glin_profanity import check_profanity, Filter

# Basic usage
result = check_profanity("This is damn good!", {
    'languages': ['english'],
    'enable_context_aware': True,
    'confidence_threshold': 0.7
})

# Filter class usage
filter_instance = Filter({
    'languages': ['english', 'spanish'],
    'enable_context_aware': True,
    'auto_replace': True,
    'replace_char': '●'
})

processed_result = filter_instance.check("Text to analyze")

# Batch processing
batch_results = filter_instance.check_multiple([
    "First text to check",
    "Second text to analyze", 
    "Third piece of content"
])

# Configuration updates
filter_instance.update_config({
    'confidence_threshold': 0.8,
    'severity_filter': 'MODERATE'
})

# Cache management
stats = filter_instance.get_cache_stats()
filter_instance.clear_cache()

Framework Integration Patterns

Web Framework Equivalents

JavaScript FrameworkPython FrameworkDescriptionDocumentation Links
Express.js MiddlewareFlask Decorator PatternNode.js web framework integrationExpress Guide | Flask Guide
Next.js API RoutesDjango Model ValidationReact framework server-side integrationNext.js Guide | Django Guide
React Hook FormsWTForms IntegrationClient-side form validationReact Forms | WTForms Example
Browser Web WorkersCelery Background TasksBackground processing in browsersWeb Workers | Celery Tasks

Error Handling Comparison

Exception and Error Patterns

JavaScript Error Handling
import { checkProfanity, ProfanityError } from 'glin-profanity';

try {
  const result = checkProfanity(text, config);
  if (result.containsProfanity) {
    console.log('Profanity detected:', result.profaneWords);
  }
} catch (error) {
  if (error instanceof ProfanityError) {
    console.error('Profanity check failed:', error.message);
    console.error('Error code:', error.code);
  } else {
    console.error('Unexpected error:', error);
  }
}

// Async error handling
try {
  const result = await checkProfanityAsync(text, config);
} catch (error) {
  console.error('Async check failed:', error);
}
Python Error Handling
from glin_profanity import check_profanity, ProfanityError

try:
    result = check_profanity(text, config)
    if result['contains_profanity']:
        print('Profanity detected:', result['profane_words'])
except ProfanityError as e:
    print(f'Profanity check failed: {e.message}')
    print(f'Error code: {e.code}')
except Exception as e:
    print(f'Unexpected error: {e}')

# Async error handling
try:
    result = await check_profanity_async(text, config)
except Exception as e:
    print(f'Async check failed: {e}')

Performance Considerations

Cross-Platform Performance Notes

  • Memory Usage: Both implementations have similar memory footprints (~2-5MB)
  • Processing Speed: JavaScript typically 10-15% faster due to V8 optimizations
  • Bundle Size: JavaScript bundle ~2.1MB, Python package ~1.8MB
  • Cold Start: Python has slightly faster cold start due to simpler initialization
  • Caching: Both implementations support identical caching strategies
  • Concurrent Processing: JavaScript uses Web Workers, Python uses multiprocessing

What's Next?


Perfect Parity: Both JavaScript and Python implementations provide identical functionality. Choose the language that best fits your project requirements - the profanity detection capabilities are exactly the same.