Interactive Number Sorting in Node.js (Insertion Sort)
Asynchronous Input Collection:
Leverages readline for user inputs, capturing integers inputted as a space-separated string.
Display Numbers:
Iterates through the collected numbers post-input and displays them, showcasing effective asynchronous data handling.
Insertion Sort Algorithm:
Employs insertion sort for sorting the user-input numbers, demonstrating in-place algorithmic sorting with outputs displayed in the console.
1class ReadlineConsole {
2    constructor() {
3        this.numbers = [];
4        this.readline = require('readline').createInterface({
5            input: process.stdin,
6            output: process.stdout
7        });
8    }
9
10    async getNumbers() {
11        const ask = async (question) => {
12            return new Promise(resolve => {
13                this.readline.question(question, resolve);
14            });
15        };
16
17        let input = await ask('Enter required number of integers separated by spaces and then press enter: ');
18        input = input.trim().replace(/\s+/g, ' '); // Remove leading/trailing spaces and consecutive spaces
19
20        let numbersArray = input.split(' ');
21
22        for (let i = 0; i < numbersArray.length; i++) {
23            let number = parseInt(numbersArray[i]);
24            if (!isNaN(number)) {
25                this.numbers.push(number);
26            }
27        }
28
29        this.readline.close();
30    }
31
32    async showNumbers() {
33        for (let i = 0; i < this.numbers.length; i++) {
34            console.log(this.numbers[i]);
35        }
36    }
37
38    async insertionSort() {
39        let arr = this.numbers;
40
41        for (let i = 1; i < arr.length; i++) {
42            let current = arr[i]
43            let j = i -1
44            while (arr[j] > current && j >= 0) {
45                arr[j+1] = arr[j]
46                j--
47            }
48            arr[j + 1] = current;
49        }
50
51        console.log(arr)
52    }
53}
54
55(async () => {
56    const readConsole = new ReadlineConsole();
57    await readConsole.getNumbers();
58    readConsole.showNumbers();
59    readConsole.insertionSort()
60})();
61
62
63