From 805c39e60c5e76b20fe667baaf0036f43ba1ed24 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Tue, 30 May 2017 22:16:27 +0900 Subject: [PATCH] refactor search function --- browser/lib/search.js | 85 +++++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 52 deletions(-) diff --git a/browser/lib/search.js b/browser/lib/search.js index ca1b5f48..3e4d0b21 100644 --- a/browser/lib/search.js +++ b/browser/lib/search.js @@ -1,62 +1,43 @@ +import _ from 'lodash' + export default function searchFromNotes(data, search) { let notes = data.noteMap.map((note) => note) if (search.trim().length === 0) return [] let searchBlocks = search.split(' ') searchBlocks.forEach((block) => { - if (block.match(/^!#.+/)) { - let tag = block.match(/^!#(.+)/)[1] - let regExp = new RegExp(_.escapeRegExp(tag), 'i') - notes = notes - .filter((note) => { - if (!_.isArray(note.tags)) return false - return note.tags.some((_tag) => { - return _tag.match(regExp) - }) - }) - } else if (block.match(/^!.+/)) { - let block = block.match(/^!(.+)/)[1] - let regExp = new RegExp(_.escapeRegExp(block), 'i') - notes = notes.filter((note) => { - if (!_.isArray(note.tags) || !note.tags.some((_tag) => { - return _tag.match(regExp) - })) { - return true - } - if (note.type === 'SNIPPET_NOTE') { - return !note.description.match(regExp) - } else if (note.type === 'MARKDOWN_NOTE') { - return !note.content.match(regExp) - } - return false - }) - } else if (block.match(/^#.+/)) { - let tag = block.match(/#(.+)/)[1] - let regExp = new RegExp(_.escapeRegExp(tag), 'i') - notes = notes - .filter((note) => { - if (!_.isArray(note.tags)) return false - return note.tags.some((_tag) => { - return _tag.match(regExp) - }) - }) + if (block.match(/^#.+/)) { + const tag = block.match(/#(.+)/)[1] + notes = findByTag(notes, tag) } else { - let regExp = new RegExp(_.escapeRegExp(block), 'i') - notes = notes.filter((note) => { - if (_.isArray(note.tags) && note.tags.some((_tag) => { - return _tag.match(regExp) - })) { - return true - } - if (note.type === 'SNIPPET_NOTE') { - return note.description.match(regExp) - } else if (note.type === 'MARKDOWN_NOTE') { - return note.content.match(regExp) - } - return false - }) + notes = findByWord(notes, block) } }) - return notes - +} + +function findByTag(notes, tag) { + let regExp = new RegExp(_.escapeRegExp(tag), 'i') + return notes.filter((note) => { + if(!_.isArray(note.tags)) return false + return note.tags.some((_tag) => { + return _tag.match(regExp) + }) + }) +} + +function findByWord(notes, block) { + let regExp = new RegExp(_.escapeRegExp(block), 'i') + return notes.filter((note) => { + if (_.isArray(note.tags) && note.tags.some((_tag) => { + return _tag.match(regExp) + })) { + return true + } + if (note.type === 'SNIPPET_NOTE') { + return note.description.match(regExp) + } else if (note.type === 'MARKDOWN_NOTE') { + return note.content.match(regExp) + } + return false + }) }