2 var assert = require('assert');
4 isNumber: require('lodash/isNumber'),
5 filter: require('lodash/filter'),
6 map: require('lodash/map'),
7 find: require('lodash/find'),
9 var Separator = require('./separator');
10 var Choice = require('./choice');
14 * Collection of multiple `choice` object
16 * @param {Array} choices All `choice` to keep in the collection
19 module.exports = class Choices {
20 constructor(choices, answers) {
21 this.choices = choices.map((val) => {
22 if (val.type === 'separator') {
23 if (!(val instanceof Separator)) {
24 val = new Separator(val.line);
30 return new Choice(val, answers);
33 this.realChoices = this.choices
34 .filter(Separator.exclude)
35 .filter((item) => !item.disabled);
37 Object.defineProperty(this, 'length', {
39 return this.choices.length;
42 this.choices.length = val;
46 Object.defineProperty(this, 'realLength', {
48 return this.realChoices.length;
51 throw new Error('Cannot set `realLength` of a Choices collection');
57 * Get a valid choice from the collection
58 * @param {Number} selector The selected choice index
59 * @return {Choice|Undefined} Return the matched choice or undefined
63 assert(_.isNumber(selector));
64 return this.realChoices[selector];
68 * Get a raw element from the collection
69 * @param {Number} selector The selected index value
70 * @return {Choice|Undefined} Return the matched choice or undefined
74 assert(_.isNumber(selector));
75 return this.choices[selector];
79 * Match the valid choices against a where clause
80 * @param {Object} whereClause Lodash `where` clause
81 * @return {Array} Matching choices or empty array
85 return _.filter(this.realChoices, whereClause);
89 * Pluck a particular key from the choices
90 * @param {String} propertyName Property name to select
91 * @return {Array} Selected properties
95 return _.map(this.realChoices, propertyName);
98 // Expose usual Array methods
100 return this.choices.indexOf.apply(this.choices, arguments);
104 return this.choices.forEach.apply(this.choices, arguments);
108 return this.choices.filter.apply(this.choices, arguments);
112 return this.choices.reduce.apply(this.choices, arguments);
116 return _.find(this.choices, func);
120 var objs = _.map(arguments, (val) => new Choice(val));
121 this.choices.push.apply(this.choices, objs);
122 this.realChoices = this.choices
123 .filter(Separator.exclude)
124 .filter((item) => !item.disabled);