Skip to content

Instantly share code, notes, and snippets.

@paulwongx
Last active May 25, 2022 01:18
Show Gist options
  • Save paulwongx/fbbe89f0198d1d3fd9185be753ff39ea to your computer and use it in GitHub Desktop.
Save paulwongx/fbbe89f0198d1d3fd9185be753ff39ea to your computer and use it in GitHub Desktop.
functions
import crypto from "crypto";
import fs from "fs";
// Creates a sha256 hash from a file
export const createHashFromFile = (filePath: string) => new Promise(resolve => {
const hash = crypto.createHash('sha256');
fs.createReadStream(filePath).on('data', data => hash.update(data)).on('end', () => resolve(hash.digest('hex')));
});
const { readFile } = require('fs').promises;
// Load a local file
async function loadFile(filepath: string) {
try {
const file = await readFile(filepath);
return JSON.parse(file.toString());
} catch (error) {
console.log('Could not load file.');
}
}
// Generates a random number between min and max inclusive on both ends
export const randomNumber = (min:number, max:number) => {
return Math.round(Math.random() * (max - min) + min);
}
// Sleep for a certain number of seconds
export const sleep = (seconds:number) =>
new Promise((resolve) => setTimeout(resolve, seconds * 1000));
// Adds the ability to Titlecase any string
String.prototype.toTitleCase = function () {
return this.toLowerCase().replace(/^.|\s\S/g, (a:string) => a.toUpperCase());
}
// Capitalizes the text in a sentence
const capitalize = (word: string) => word.replace(/(^|\s)\S/g, l => l.toUpperCase());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment