all files / lib/ menu.js

100% Statements 39/39
87.5% Branches 14/16
100% Functions 10/10
100% Lines 36/36
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77   18×                                                         13×   12×                      
var stdin = process.stdin;
var stdout = process.stdout;
 
function printTitleAndOptions(title, options) {
    stdout.write(title + ':\n');
    for(var i = 0; i < options.length; i++) {
        stdout.write((i + 1) + ') ' + options[i].title + '\n');
    }
}
 
function build(func, title, options, callback) {
    return function() {
        func(title, options, callback);
    };
}
 
/**
 * Prints a single-choice menu
 * @param title (String)
 * @param options (options Object)
 * @param callback (Function)
 */
function single(title, options, callback) {
    printTitleAndOptions(title, options);
 
    stdin.addListener('data', function (e) {
        var choose = parseInt(e.toString().trim(), 10);
        if (choose) {
            choose--;
            if (choose < 0 || choose >= options.length) {
                stdout.write('Invalid option\n');
            } else {
                stdin.removeAllListeners('data');
                options[choose].action();
                Eif(callback) {
                    return callback();
                }
            }
        } else {
            stdout.write('Invalid option\n');
        }
    });
}
 
/**
 * Prints a multi-choice menu
 * @param title (String)
 * @param options (options Object)
 * @param callback (Function)
 */
function multi(title, options, callback) {
    printTitleAndOptions(title, options);
 
    var stdin = process.openStdin();
    stdin.addListener('data', function (e) {
        var chooseStr = e.toString().replace(/\s+/g, ' ').trim().split(' ');
        var choose = chooseStr.map(function(i) { return parseInt(i, 10); });
 
        var valid = choose.every(function(i) {return i && !(i < 0 || i > options.length); });
 
        if(valid) {
            stdin.removeAllListeners('data');
            choose.forEach(function(c) { options[c - 1].action(); });
            Eif(callback) {
                return callback();
            }
        } else {
            stdout.write('Invalid option\n');
        }
    });
}
 
module.exports = {
    build: build,
    single: single,
    multi: multi
};