cache | cell cache | test cache notebook | Search

Run example

npm run import -- "cache notebook"

cache notebook

var path = require('path');
var fs = require('fs')
var importer = require('../Core')
var MATCH_QUESTIONS = (/^.*\?.*$/igm);

function getQuestions(source, markdown) {
    var questions = importer.regexToArray(MATCH_QUESTIONS, markdown)
        .map(r => r.replace(/how to|\?|#+/ig, '').trim())
        .concat(importer.regexToArray(MATCH_QUESTIONS, source)
            .filter(r => r.match(/how to/ig))
            .map(r => r.replace(/how to|\?|#+/ig, '').trim()))
        // find the shortest words from the query to match the same cell
    questions.sort((a, b) => a.length - b.length)
    // TODO: weird fix, Fuse.js apparently doesn't work on lists with one element
    return questions[0] ? questions.concat(questions[0]) : questions;
}

// TODO: convert to pattern like group everything leading up to match
function accumulateMarkdown(cells) {
    // read markdown leading up to code cells
    var codes = cells.filter(c => c.cell_type === 'code')
    return codes
        .map((c, i) => Object.assign(c, {
            from: i > 0 ? (cells.indexOf(codes[i-1]) + 1) : 0,
            to: cells.indexOf(c)
        }))
        .map((c, i) => Object.assign(c, {
            markdown: cells.slice(c.from, c.to).map(m => m.source.join('')),
            code: c.source.join('')
        }))
}

function cacheCells(filename) {
    filename = path.resolve(filename)
    const mtime = fs.statSync(filename).mtime.getTime()
    const cells = importer.getCells(filename, ['*', 'markdown', 'code'])
    const newCache = accumulateMarkdown(cells)
    return newCache.map((c, i) => {
        var id = path.basename(filename) + '[' + i + ']'
        var questions = getQuestions(c.code, c.markdown)
        if(questions.length === 0) questions = ['']
        return Object.assign(c, {
            id,
            filename,
            mtime,
            questions,
            notebook: path.basename(filename)
        })
    })
}

module.exports = {
    cacheCells,
    accumulateMarkdown,
    getQuestions,
}