the-honk/challenges/euler/scripts/run.js

110 lines
2.6 KiB
JavaScript
Raw Normal View History

2024-10-09 17:02:34 +00:00
const fs = require('fs');
const chalk = require('chalk');
2024-10-09 17:02:37 +00:00
const { spawnSync } = require('child_process');
const executionTime = require('execution-time')();
const ms = require('ms');
2024-10-09 17:02:34 +00:00
2024-10-09 17:02:37 +00:00
const generateBanner = text => {
// Calculate the length of the divider
2024-10-09 17:02:34 +00:00
let divider = '--';
2024-10-09 17:02:37 +00:00
for (let j = 0; j < text.length; j++) {
2024-10-09 17:02:34 +00:00
divider += '-';
}
2024-10-09 17:02:37 +00:00
return `${divider}
${chalk.bold(chalk.greenBright(text))}
${divider}`;
};
const run = file => {
console.log(generateBanner(file.split('.ts')[0]));
2024-10-09 17:02:34 +00:00
2024-10-09 17:02:35 +00:00
// Execute the file
executionTime.start();
2024-10-09 17:02:37 +00:00
spawnSync('npx', ['ts-node', `"src/${file}"`], {
shell: true,
stdio: 'inherit'
});
const results = executionTime.stop();
2024-10-09 17:02:35 +00:00
// Print time results
console.log();
console.log(chalk.bold(chalk.yellow(`Executed in ${results.words}`)));
return results.time;
};
const runMany = files => {
let totalTime = 0;
files.forEach(file => {
const time = run(file);
totalTime += time;
console.log();
});
console.log(
chalk.magenta(
chalk.bold(
`This set of executions took roughly ${ms(totalTime, { long: true })} in total!`
)
)
);
2024-10-09 17:02:34 +00:00
};
2024-10-09 17:02:37 +00:00
// Get files
const allFiles = fs
2024-10-09 17:02:37 +00:00
.readdirSync('src')
.filter(f => f.endsWith('.ts'))
.filter(f => f !== 'utils.ts');
2024-10-09 17:02:34 +00:00
2024-10-09 17:02:37 +00:00
// Extract the puzzle number
process.argv.shift();
process.argv.shift();
if (process.argv[0] === 'all' || process.argv.length === 0) {
const files = allFiles.sort((a, b) => {
a = parseInt(a.split('-')[0]);
b = parseInt(b.split('-')[0]);
return a > b ? 1 : -1;
});
runMany(files);
} else if (process.argv.length > 1 || process.argv[0].includes(',')) {
let puzzleNumbers = process.argv
.map(v =>
v.includes(',')
? v.split(',').map(e => (!isNaN(e) ? parseInt(e) : null))
: !isNaN(v)
? parseInt(v)
: null
)
.flat()
.filter(e => e !== null);
puzzleNumbers = puzzleNumbers.filter((e, i) => puzzleNumbers.indexOf(e) === i);
const files = allFiles.filter(f =>
f.match(
`^(?:[${puzzleNumbers.map((number, i) =>
i === puzzleNumbers.length - 1 ? number : `${number}|`
)}]) -`
)
);
runMany(files);
} else if (!isNaN(process.argv[0])) {
2024-10-09 17:02:37 +00:00
// Find the associated puzzle
const [file] = allFiles.filter(f => f.startsWith(process.argv[0]));
2024-10-09 17:02:37 +00:00
run(file);
} else {
console.log(
chalk.bold(
chalk.red('Please ensure that you input the number of the puzzle to run - thank you.')
)
);
}