jisho-sidekick
Version:
Japanese reading sidekick integrating Jisho and Memrise
105 lines (96 loc) • 2.9 kB
JavaScript
const _ = require('lodash')
const colors = require('colors')
const inquirer = require('inquirer')
const jisho = require('./lib/jisho')
function chooseResult(resultSet) {
if (resultSet.length === 1) {
console.log(`Only one result found: ${resultSet[0].japanese[0].word.cyan}: ${resultSet[0].japanese[0].reading.yellow}`)
return resultSet[0]
}
return inquirer.prompt([{
type: 'list',
name: 'result',
message: `Please choose a result:`,
choices: _.map(resultSet, (result, i) => ({
name: `${result.japanese[0].word || 'No kanji'}: ${result.japanese[0].reading}: ${result.senses[0].english_definitions[0]}`,
value: i,
short: result.japanese[0].word,
})),
}]).then(choiceHash => resultSet[choiceHash.result])
}
function chooseSense(r) {
if (r.senses.length === 1) {
console.log(`Only one sense found: ${r.senses[0].english_definitions[0].cyan}`)
return r.senses[0]
}
return inquirer.prompt([{
type: 'list',
name: 'sense',
message: `Found ${r.senses.length} senses, please choose one:`,
choices: _.map(r.senses, (sense, i) => ({
name: `${_.map(sense.english_definitions, def => def).join(', ')} [${sense.parts_of_speech.join(', ')}]`,
value: i,
})),
},])
.then(choices => ({
japanese: {
common: r.japanese[0].word,
reading: r.japanese[0].reading,
},
definitions: r.senses[choices.sense].english_definitions,
kanaAlone: r.senses[choices.sense].kanaAlone,
}))
}
function formatForOutput(results) {
let csv = '---CSV for bulk upload---\n'
for (let word of results) {
console.log(word)
let line = ''
// Common Japanese
line = `${line}${word.kanaAlone ? word.japanese.reading : word.japanese.common}\t`
// Kana
line = `${line}${word.japanese.reading}\t`
// English
line = `${line}${word.definitions[0]}\n`
// Add to CSV
csv = `${csv}${line}`
}
csv = `${csv}---END---`
return csv
}
function getSearchTerm() {
return inquirer.prompt({
type: 'input',
name: 'term',
message: 'Enter a Jisho search term:'
}).then(choices => choices.term)
}
function logSearching(term) {
console.log(`Searching Jisho for ${term.cyan}...`)
return term
}
function restartOrFinish() {
return inquirer.prompt([{
type: 'confirm',
name: 'continue',
message: 'Would you like to continue?',
}]).then(choices => choices.continue)
}
function sidekick(gatheredResults=[]) {
return (
getSearchTerm()
.then(logSearching)
.then(jisho.search)
.then(chooseResult)
.then(chooseSense)
.then(res => {if (!!res) {gatheredResults.push(res)}})
.then(restartOrFinish)
.then(restart => restart ? sidekick(gatheredResults) : gatheredResults)
.then(formatForOutput)
.catch(err => {
console.error(err)
return sidekick(gatheredResults)
})
)
}
module.exports = sidekick;