From 9be1236a2f1e81b76b755ffa5a7bad9e9af2db73 Mon Sep 17 00:00:00 2001 From: Cyn Date: Sat, 25 Dec 2021 17:15:57 -0500 Subject: [PATCH] Fix hashing function --- src/watcher.ts | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/watcher.ts b/src/watcher.ts index 43ba503..2dd0772 100644 --- a/src/watcher.ts +++ b/src/watcher.ts @@ -1,31 +1,31 @@ -import { NS, ProcessInfo } from "../NetscriptDefinitions" +import { NS, ProcessInfo } from '../NetscriptDefinitions' -export async function main(ns : NS) : Promise { - const hashes : any = {} +export async function main(ns: NS): Promise { + const hashes: any = {} - const files = ns.ls('home', '.js') - for ( const file of files ) { + const files = ns.ls('home', '.js') + for (const file of files) { const contents = ns.read(file) hashes[file] = getHash(contents) } - while(true) { + while (true) { const files = ns.ls('home', '.js') - for(const file of files ) { + for (const file of files) { const contents = ns.read(file) const hash = getHash(contents) - if(hash != hashes[file]) { + if (hash != hashes[file]) { ns.tprint(`INFO: Detected change in ${file}`) - const processes = ns.ps().filter((p : ProcessInfo) => { + const processes = ns.ps().filter((p: ProcessInfo) => { return p.filename == file }) - for(const process of processes) { - if(process.filename != ns.getScriptName()) { - ns.tprint(`INFO: Restarting ${process.filename} ${process.args} -t ${process.threads}`) + for (const process of processes) { + ns.tprint(`INFO: Restarting ${process.filename} ${process.args} -t ${process.threads}`) + if (process.filename != ns.getScriptName()) { ns.kill(process.pid, ns.getHostname()) ns.run(process.filename, process.threads, ...process.args) } else { @@ -41,6 +41,13 @@ export async function main(ns : NS) : Promise { } } -function getHash(input : string) : number { - return input.split("").reduce( (a, b) => ((a << 5) - 1) + b.charCodeAt(0)|0, 0) +const getHash = (input: string): number => { + let hash = 0, i, chr + if (input.length === 0) return hash + for (i = 0; i < input.length; i++) { + chr = input.charCodeAt(i) + hash = ((hash << 5) - hash) + chr + hash |= 0 // Convert to 32bit integer + } + return hash } \ No newline at end of file