const uuidV4 = require('uuid/v4');
const _ = require('lodash');
const Word = require('./word');


let words = new WeakMap();
class Sentence {
  constructor(paragraphId, text, index) {
    this.id = uuidV4();
    this.index = index;
    this.paragraphId = paragraphId;
    this.text = text;
    this.parseWords();
    return this;
  }

  get words() {
    return _.map(words.get(this), 'id');
  }

  set words(w) {
    words.set(this, w);
  }

  get wordsObject() {
    return words.get(this);
  }

  parseWords() {
    let {id: sentenceId, text} = this;
    this.words = _.chain(text).split(/\s{1,}/ig)
      .map((text, index) => new Word(sentenceId, index, text)).value();
  }
}

module.exports = Sentence;

const uuidV4 = require('uuid/v4');
const _ = require('lodash');
const Word = require('./word');


let words = new WeakMap();
let parent = new WeakMap();

class Sentence {
  constructor(paragraph, text, index) {
    parent.set(this, paragraph);

    this.id = uuidV4();
    this.index = index;
    this.paragraphId = paragraph.id;
    this.text = text;
    this.parseWords();
    return this;
  }

  parent() {
    return parent.get(this);
  }

  findWordById(id) {
    return _.find(this.wordsCollection, {id});
  }

  findWordByIndex(index) {
    return _.find(this.wordsCollection, {index});
  }

  next() {
    let index = this.index;
    return this.parent().findSentenceByIndex(index + 1);
  }

  prev() {
    let index = this.index;
    return this.parent().findSentenceByIndex(index - 1);
  }

  get words() {
    return _.map(words.get(this), 'id');
  }

  set words(w) {
    words.set(this, w);
  }

  get wordsCollection() {
    return words.get(this);
  }

  parseWords() {
    let sentence = this;
    let {text} = sentence;
    this.words = _.chain(text).split(/\s{1,}/ig)
      .map((text, index) => new Word(sentence, index, text)).value();
  }
}

module.exports = Sentence;

Add more methods and Refactor code
Add more methods and Refactor code

Constructor now accept first argument as paragraph parent. Also create a reference from its parent.

parseWords now pass a sentence rather than sentenceId.

parent() method get paragraph parent from a sentence.

This commit also introduce lookup methods, they are:
- findWordById = find a word by its id
- findWordByIndex = find a word by its index

Sentence has navigate method too:
- next() is for navigating to the next sentence in a paragraph context.
- prev() is for navigating to the previous sentence in a paragraph context.