Оптимизируй мой алгоритм:
const xlsx = require('node-xlsx');
const fs = require('fs');
const { isNumber } = require('util');
const sqlite3 = require('sqlite3').verbose();
const cron = require('node-cron');

const db = new sqlite3.Database('schedule.db');

const workSheetsFromBuffer1 = xlsx.parse(fs.readFileSync(`${__dirname}/excels/odd.xlsx`));
const workSheetsFromBuffer2 = xlsx.parse(fs.readFileSync(`${__dirname}/excels/even.xlsx`));
let teachers = []
const arr1 = workSheetsFromBuffer1[1].data
const arr2 = workSheetsFromBuffer2[1].data
teachers = [...arr1,...arr2]

function transformArray(arr,len) {
    return Array.from({ length: len}, (_, i) => arr[i] !== undefined ? arr[i] : 'null');
}
function replaceNextAfterPhysicalCulture(teachers) {
    teachers.forEach((element,index) => {
        if (typeof element === 'string') {
            if (element.indexOf("Физическая культура")!==-1) {
                teachers[index + 1] = 'зал';
            }
        }
    });
    return teachers
}
function splitGroupAndSubject(input, cab) {
    if (typeof input !== 'string') return input;
    try {
        const groupRegex = /(\d{2,3}[- ]?[А-Яа-яA-Za-z]{1,2}[- ]?\d{2})/g;
        const subjectRegex = /(?:\d{2,3}[- ]?[А-Яа-яA-Za-z]{1,2}[- ]?\d{2}[\s,]*)*(.*)/;

        const groups = input.match(groupRegex) || [];
        const subjectMatch = input.match(subjectRegex);
        const subject = subjectMatch ? subjectMatch[1].trim() : '';

        const filteredSubject = subject.split(' ')
            .filter(word => !/\d/.test(word))
            .join(' ')
            .replace(/^-+/, '')
            .replace(/.*-/, '').trim();

        return { groups, subject: filteredSubject.trim(), cab: String(cab) };
    } catch (error) {
        console.log("error", input);
    }
}

function parseteachers() {
    let parsedIndex = [];

    for (let index = 0; index < teachers.length; index++) {
        let item = teachers[index];
        if (!item || item.length === 0) continue;

        let teacherName = parseTeacherName(item);
        if (!teacherName) continue;

        let later = findScheduleType(index);
        index += 3;

        let pairs = parsePairs(index);
        parsedIndex.push({ teacherName, later, pairs });
    }

    parsedIndex.forEach((entry,index) => {
        let newPairs = []
        entry.pairs.forEach((pair, index) => {
            const result = [pair[0]]
    
            for (let index = 1; index < pair.length; index++) {
                const subject = pair[index];
                const cab = pair[index+1];index++;
                result.push(splitGroupAndSubject(subject, cab));
            }
            
            newPairs.push(result)
        })
        parsedIndex[index].pairs = newPairs
    })

    return parsedIndex;

    function parseTeacherName(item) {
        let firstItem = item[0];
        if (typeof firstItem === 'string' && firstItem.includes("Преподаватель")) {
            return firstItem.replace("Преподаватель - ", "").trim();
        }
        return null;
    }

    function findScheduleType(index) {
        let item = teachers[index];
        while (item && item[0] !== 'Нечетная неделя' && item[0] !== 'Четная неделя') {
            index++;
            item = teachers[index];
        }
        return item[0] === 'Нечетная неделя' ? 'odd' : 'even';
    }

    function parsePairs(startIndex) {
        let pairs = [];
        let emptyCount = 0;
        let maxPairs = 0;

        for (let i = startIndex; emptyCount < 2; i++) {
            let item = teachers[i];
            if (!item || item[0] === undefined) {
                emptyCount++;
                continue;
            }

            emptyCount = 0;
            if (isNumber(item[0])) {
                let pair = transformArray(item, 13);
                pair = replaceNextAfterPhysicalCulture(pair);
                pairs.push(pair);

                if (item[0] > maxPairs) maxPairs = item[0];
            }
        }

        return pairs;
    }
}

const data = parseteachers()

db.serialize(() => {
    db.run(`DROP TABLE IF EXISTS schedule`);
    db.run(`DROP TABLE IF EXISTS groups_schedule`);
    db.run(`DROP TABLE IF EXISTS rooms_schedule`);
  
    db.run(`
      CREATE TABLE IF NOT EXISTS schedule (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        teacherName TEXT,
        later TEXT,
        pairNumber INTEGER,
        dayOfWeek TEXT,
        groups TEXT,
        subject TEXT,
        cab TEXT
      )
    `);
  
    db.run(`
      CREATE TABLE IF NOT EXISTS groups_schedule (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        groupName TEXT,
        dayOfWeek TEXT,
        pairNumber INTEGER,
        subject TEXT,
        teacherName TEXT,
        cab TEXT
      )
    `);
  
    db.run(`
      CREATE TABLE IF NOT EXISTS rooms_schedule (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        cab TEXT,
        dayOfWeek TEXT,
        pairNumber INTEGER,
        subject TEXT,
        teacherName TEXT,
        groups TEXT,
        isFree BOOLEAN DEFAULT 1
      )
    `);
  
    const insertSchedule = db.prepare(`
      INSERT INTO schedule (teacherName, later, pairNumber, dayOfWeek, groups, subject, cab) 
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `);
  
    const insertGroupSchedule = db.prepare(`
      INSERT INTO groups_schedule (groupName, dayOfWeek, pairNumber, subject, teacherName, cab) 
      VALUES (?, ?, ?, ?, ?, ?)
    `);
  
    const insertRoomSchedule = db.prepare(`
      INSERT INTO rooms_schedule (cab, dayOfWeek, pairNumber, subject, teacherName, groups, isFree)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `);
  
    const daysOfWeek = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'];
  
    // Заполнение rooms_schedule по умолчанию
    const allCabinets = new Set(data.flatMap(teacher => teacher.pairs.map(pair => pair[1].cab)));
    allCabinets.forEach(cab => {
      daysOfWeek.forEach(day => {
        for (let i = 1; i <= 6; i++) {
          if (cab!== "null" || cab === "-") {
            insertRoomSchedule.run(cab, day, i, "-", "-", "-", true);
          }
        }
      });
    });
  
    // Добавление расписания
    data.forEach(teacher => {
      teacher.pairs.forEach(pair => {
        const pairNumber = pair[0];
        pair.slice(1).forEach((day, index) => {
          insertSchedule.run(
            teacher.teacherName,
            teacher.later,
            pairNumber,
            daysOfWeek[index],
            day.groups.join(', '),
            day.subject,
            day.cab
          );
  
          day.groups.forEach(group => {
            insertGroupSchedule.run(
              group,
              daysOfWeek[index],
              pairNumber,
              day.subject,
              teacher.teacherName,
              day.cab
            );
          });
  
          if (day.cab !== "null" && day.cab !== "-") {
            db.run(`
              UPDATE rooms_schedule 
              SET isFree = 0, subject = ?, teacherName = ?, groups = ? 
              WHERE cab = ? AND dayOfWeek = ? AND pairNumber = ?
            `, [day.subject, teacher.teacherName, day.groups.join(', '), day.cab, daysOfWeek[index], pairNumber]);
          }
        });
      });
    });
  
    insertSchedule.finalize();
    insertGroupSchedule.finalize();
    insertRoomSchedule.finalize();
});

db.close();