Created
March 31, 2024 04:27
-
-
Save wolfram77/42e2a4fb75d72534142db4f5409159a2 to your computer and use it in GitHub Desktop.
Add self-loops to a graph file : SCRIPT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const readline = require('readline'); | |
// Read the header of a graph file. | |
async function readGraphHeader(pth) { | |
var fstream = fs.createReadStream(pth); | |
var rl = readline.createInterface({input: fstream, crlfDelay: Infinity}); | |
for await (var ln of rl) { | |
if (ln.startsWith('%')) continue; | |
var [rows, cols, size] = ln.split(' ').map(parseFloat); | |
rl.close(); | |
fstream.close(); | |
return {rows, cols, size}; | |
} | |
rl.close(); | |
fstream.close(); | |
return {rows: 0, cols: 0, size: 0}; | |
} | |
// Read the last n bytes of a file. | |
function readFileTail(pth, n) { | |
var fd = fs.openSync(pth, 'r'); | |
var stats = fs.fstatSync(fd); | |
var buf = Buffer.alloc(n); | |
fs.readSync(fd, buf, 0, n, stats.size-n); | |
fs.closeSync(fd); | |
return buf.toString(); | |
} | |
// Add self-loops to a graph file. | |
async function addSelfLoops(inp, out) { | |
var {rows} = await readGraphHeader(inp); | |
var tail = readFileTail(inp, 2); | |
fs.copyFileSync(inp, out); | |
var fstream = fs.createWriteStream(out, {flags: 'a'}); | |
if (/\r$|\r?\n$/.test(tail)) fstream.write('\n'); | |
for (var i=0; i<rows; i++) | |
fstream.write(`${i} ${i}\n`); | |
fstream.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment