All files / lib/md write.js

84.78% Statements 39/46
78.95% Branches 15/19
100% Functions 6/6
84.78% Lines 39/46
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98  1x 1x               3x 3x 2x     1x 1x 1x 1x 1x       6x 1x 1x 1x     5x         5x   2x 2x     3x 3x                 2x 1x 1x 1x     1x 1x 1x 1x       3x         3x 1x 1x 1x     2x               2x 2x           2x 2x           1x  
'use strict';
const stream = require('stream');
const todo = require('../todo');
 
/*
 * PUBLIC API
 */
 
class Writer extends stream.Readable {
  constructor(object) {
    super('utf8');
    if (!(object instanceof todo.Project)) {
      throw new TypeError('Expecting object of type todo.Project');
    }
 
    this._object = object;
    this._state = 0;
    this._listCount = 0;
    this._itemCount = 0;
    this._currentList = null;
  }
 
  _read() {
    if (this._state === 0) {
      this.push(serializeParagraph(this._object.title, this._object.desc) + '\n');
      ++this._state;
      return;
    }
 
    Iif (this._state === -1) {
      this.push(null);
      return;
    }
 
    switch (this._state) {
      case 1:
        this._sendParagraph();
        break;
 
      case 2:
        this._sendList();
        break;
 
      default:
        this.emit('error', new Error('Internal error'));
        break;
    }
  }
 
  _sendParagraph() {
    if (this._listCount >= this._object.length) {
      this._state = -1;
      this.push(null);
      return;
    }
 
    this._currentList = this._object.getList(this._listCount++);
    this._itemCount = 0;
    this.push('#' + serializeParagraph(this._currentList.title, this._currentList.desc));
    ++this._state;
  }
 
  _sendList() {
    Iif (this._currentList === null) {
      this.emit('error', new TypeError('Internal error'));
      return;
    }
 
    if (this._itemCount >= this._currentList.length) {
      this.push('\n');
      --this._state;
      return;
    }
 
    this.push(serializeListItem(this._currentList.getItem(this._itemCount++)));
  }
}
 
/*
 * PRIVATE FUNCTIONS
 */
function serializeParagraph(title, desc) {
  Eif (desc.length !== 0) {
    return '# ' + title + '\n' + desc + '\n';
  }
  return '# ' + title + '\n';
}
 
function serializeListItem(item) {
  const status = item.done ? 'X' : ' ';
  return '  - [' + status + '] ' + item.value + '\n';
}
 
/*
 * MODULE EXPORTS
 */
module.exports = Writer;