3 const StringPrompt = require('./string');
5 class NumberPrompt extends StringPrompt {
6 constructor(options = {}) {
7 super({ style: 'number', ...options });
8 this.min = this.isValue(options.min) ? this.toNumber(options.min) : -Infinity;
9 this.max = this.isValue(options.max) ? this.toNumber(options.max) : Infinity;
10 this.delay = options.delay != null ? options.delay : 1000;
11 this.float = options.float !== false;
12 this.round = options.round === true || options.float === false;
13 this.major = options.major || 10;
14 this.minor = options.minor || 1;
15 this.initial = options.initial != null ? options.initial : '';
16 this.input = String(this.initial);
17 this.cursor = this.input.length;
22 if (!/[-+.]/.test(ch) || (ch === '.' && this.input.includes('.'))) {
23 return this.alert('invalid number');
25 return super.append(ch);
29 return super.append(ch);
33 if (this.input && this.input !== this.initial) return this.alert();
34 if (!this.isValue(this.initial)) return this.alert();
35 this.input = this.initial;
36 this.cursor = String(this.initial).length;
41 let step = number || this.minor;
42 let num = this.toNumber(this.input);
43 if (num > this.max + step) return this.alert();
44 this.input = `${num + step}`;
49 let step = number || this.minor;
50 let num = this.toNumber(this.input);
51 if (num < this.min - step) return this.alert();
52 this.input = `${num - step}`;
57 return this.down(this.major);
61 return this.up(this.major);
64 format(input = this.input) {
65 if (typeof this.options.format === 'function') {
66 return this.options.format.call(this, input);
68 return this.styles.info(input);
71 toNumber(value = '') {
72 return this.float ? +value : Math.round(+value);
76 return /^[-+]?[0-9]+((\.)|(\.[0-9]+))?$/.test(value);
80 let value = [this.input, this.initial].find(v => this.isValue(v));
81 this.value = this.toNumber(value || 0);
82 return super.submit();
86 module.exports = NumberPrompt;