Сейчас попросил грока сделать скриптик для небольшой автоматизации.
Он выступил на отлично. Надо чаще к нему обращаться с такими
вопросами:
ส็็็็็็็็็็็็็็็็็็็็็็็็็༼ ຈل͜ຈ༽ส้้้้้้้้้้้้้้้้้้้้้้้
- There are some text files in current directory. Each contains 2 columns of numbers separated by TAB. Number of rows is the same in them. The first column is identical. Write a script in Node.js that creates a text file that preserves the first column and adds the second column from each file, so resulting number of columns is (number of files)+1. Also prepend a row above each column except first with the file name minus the extension.
Выдал скрипт на 100 строк, работает. Прошу сделать покороче:
- It works. Can you make the script smaller? I don't need any checks, just assume the input is of correct form.
Выдал скрипт в 4 раза короче. Красиво:
#!/usr/bin/env node
import { readdirSync, readFileSync, writeFileSync } from 'fs';
import { basename, extname } from 'path';
const outFileName = 'merged.txt';
const files = readdirSync('.')
.filter(f => f.endsWith('.txt') && f !== outFileName)
.sort();
const data = files.map(f => ({
name: basename(f, extname(f)),
lines: readFileSync(f, 'utf8').trim().split(/\r?\n/)
}));
const header = ['', ...data.map(d => d.name)].join('\t');
const rows = data[0].lines.map((_, i) => {
const firstCol = _.split('\t')[0];
const seconds = data.map(d => d.lines[i].split('\t')[1]);
return [firstCol, ...seconds].join('\t');
});
writeFileSync(outFileName, [header, ...rows].join('\n') + '\n');
console.log(`Done → merged.txt (${rows.length} rows, ${files.length + 1} columns)`);