All files metadata-extractor.ts

100% Statements 16/16
100% Branches 4/4
100% Functions 1/1
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 322x                 6x 4x 4x 4x 4x   4x   4x 3x 3x   3x   3x 3x     4x   4x    
import { safeLoad } from 'js-yaml';
 
import { MarkdownMetadata, MarkdownMetadataContent } from './interface';
 
/** *
 * Extract the metadata from the content
 *
 * The metadata should be wrapped with the delimiter
 */
export function extract(contents: string, delimiter = '---'): MarkdownMetadataContent {
  const ZERO = 0;
  let startIndex = ZERO;
  let endIndex = ZERO;
  let metadata = {};
 
  const input = contents.trim();
 
  if (input.indexOf(delimiter) === ZERO) {
    startIndex = input.indexOf(delimiter) + delimiter.length;
    endIndex = input.indexOf(delimiter, startIndex);
 
    const mdMetadata = input.substring(startIndex, endIndex);
 
    metadata = safeLoad(mdMetadata) as MarkdownMetadata;
    endIndex += delimiter.length;
  }
 
  const content = input.substring(endIndex).trim();
 
  return { metadata, content };
}