From 99228f2e60f41ac29ea788696e6fcbc7d1db4b22 Mon Sep 17 00:00:00 2001 From: asmsuechan Date: Tue, 23 May 2017 16:51:58 +0900 Subject: [PATCH] :recycle: Refactor findeTitle() --- browser/lib/findNoteTitle.js | 22 +++++++++------------- tests/lib/find-title-test.js | 7 ++++--- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/browser/lib/findNoteTitle.js b/browser/lib/findNoteTitle.js index e7253db3..46238caf 100644 --- a/browser/lib/findNoteTitle.js +++ b/browser/lib/findNoteTitle.js @@ -1,29 +1,25 @@ export function findNoteTitle (value) { let splitted = value.split('\n') let title = null - let isMarkdownInCode = false + let isInsideCodeBlock = false splitted.some((line, index) => { let trimmedLine = line.trim() let trimmedNextLine = splitted[index + 1] === undefined ? '' : splitted[index + 1].trim() if (trimmedLine.match('```')) { - isMarkdownInCode = !isMarkdownInCode - } else if (isMarkdownInCode === false && (trimmedLine.match(/^# +/) || trimmedNextLine.match('='))) { - if (trimmedNextLine.match('=')) { - title = trimmedLine.substring(0, trimmedLine.length).trim() - } else { - title = trimmedLine.substring(1, trimmedLine.length).trim() - } + isInsideCodeBlock = !isInsideCodeBlock + } + if (isInsideCodeBlock === false && (trimmedLine.match(/^# +/) || trimmedNextLine.match(/^=+$/))) { + title = trimmedLine return true } }) - if (title == null) { + if (title === null) { title = '' - splitted.some((line, index) => { - let trimmedLine = splitted[index].trim() - if (trimmedLine.length > 0) { - title = trimmedLine + splitted.some((line) => { + if (line.trim().length > 0) { + title = line.trim() return true } }) diff --git a/tests/lib/find-title-test.js b/tests/lib/find-title-test.js index e2aad48b..2c91a3dc 100644 --- a/tests/lib/find-title-test.js +++ b/tests/lib/find-title-test.js @@ -9,9 +9,10 @@ const { findNoteTitle } = require('browser/lib/findNoteTitle') test('findNoteTitle#find should return a correct title (string)', t => { // [input, expected] const testCases = [ - ['# hoge\nfuga', 'hoge'], - ['# hoge_hoge_hoge', 'hoge_hoge_hoge'], - ['```\n# hoge\n```\n# fuga', 'fuga'], + ['# hoge\nfuga', '# hoge'], + ['# hoge_hoge_hoge', '# hoge_hoge_hoge'], + ['hoge\n====\nfuga', 'hoge'], + ['====', '===='], ['```\n# hoge\n```', '```'], ['hoge', 'hoge'] ]