Skip to content

Instantly share code, notes, and snippets.

@daryl-sf
Last active February 22, 2023 12:15
Show Gist options
  • Save daryl-sf/e2867b49fbf4513821946c998c77d512 to your computer and use it in GitHub Desktop.
Save daryl-sf/e2867b49fbf4513821946c998c77d512 to your computer and use it in GitHub Desktop.
hash function gist
const crypto = require("crypto");
function hash(data, callback) {
let counter = 0;
let result = [];
let func = () => {
if(counter === data.length) {
callback(result);
return;
}
let md5 = crypto.createHash("md5");
md5.update(data[counter]);
result.push(md5.digest('hex'));
counter++;
// process.nextTick adds to the micro task queue which is always executed before the task queue (timer functions push to task queue).
// changing this to setTimeout will satisfy unblocking the event loop
setTimeout(func);
};
func();
}
hash(["test", "another test", ""], console.log);
setTimeout(() => {
setTimeout(() => console.log("This should be printed before the hashes"));
});
/* should print
['098f6bcd4621d373cade4e832627b4f6',
'5e8862cd73694287ff341e75c95e3c6a',
'd41d8cd98f00b204e9800998ecf8427e'] */
module.exports.hash = hash;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment