Skip to content

fix: return neutral sentiment for empty input - #813

Open
xiaoyao-666-coder wants to merge 1 commit into
NaturalNode:masterfrom
xiaoyao-666-coder:fix/sentiment-empty-input
Open

xiaoyao-666-coder wants to merge 1 commit into
NaturalNode:masterfrom
xiaoyao-666-coder:fix/sentiment-empty-input

Conversation

@xiaoyao-666-coder

@xiaoyao-666-coder xiaoyao-666-coder commented Nov 14, 2026 •

Copy link
Copy Markdown

getSentiment([]) returns NaN because the accumulated score is divided by zero. This also affects normal tokenizer pipelines: empty, whitespace-only, and punctuation-only text produces no words with WordTokenizer.

const { SentimentAnalyzer, PorterStemmer, WordTokenizer } = require('natural')
const analyzer = new SentimentAnalyzer('English', PorterStemmer, 'afinn')
const words = new WordTokenizer().tokenize('...!?') // []
analyzer.getSentiment(words) // before: NaN; after: 0

Proposed Changes

  • Return the neutral score 0 when the input array is empty, before dividing by its length.
  • Add eight Jasmine regressions covering all four vocabulary types, a supplied stemmer, and empty tokenizer output.

Nonempty inputs follow the existing scoring path. No public signature or TypeScript declaration changes are needed.

Validation

On Node 24.22.1 / Windows:

  • New tests against unmodified source: 20 specs, 8 failures (NaN instead of 0)
  • Fixed sentiment suite: 20 specs, 0 failures
  • npm test: 906 specs, 0 failures
  • npm run build:tests and npm run lint
  • Standard JS and focused jscpd check for SentimentAnalyzer.js
  • npm run build:esm and npm run smoke:esm
  • git diff --check

The database-backed I/O suite was not run. Companion documentation targets gh-pages in #814, as required by CONTRIBUTING.md.

Checklist before merging

  • Added Jasmine tests
  • TypeScript declarations: no signature changes required

Prepared with Codex assistance.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant