Skip to content

Instantly share code, notes, and snippets.

@witt3rd
Last active June 13, 2019 15:23
Show Gist options
  • Save witt3rd/d0182f6681017c0754d03219798fb507 to your computer and use it in GitHub Desktop.
Save witt3rd/d0182f6681017c0754d03219798fb507 to your computer and use it in GitHub Desktop.
Useful code snippets in JavaScript
const fs = require("fs-extra");
const Path = require("path");
//
// String utilities
//
// Ensure initial letter is capitalized
const capitalize = word => word[0].toUpperCase() + word.substr(1);
// Strip newlines from string
const stripCRLF = s => s.replace(/\r?\n|\r/g, "");
// Truncate text with an ellipse
const ellipse = (str, max = 200) => {
if (str.length > max) {
return str.substring(0, max) + "...";
}
return str;
};
const parseTime = time => {
const currentDateString = new Date().toISOString();
return new Date(
currentDateString.substr(0, currentDateString.indexOf("T") + 1) + time
);
};
/**
* Update the set of values for this indexed collection
*/
const append = (obj, k, v) => {
let e = obj[k];
if (!e || e.length === 0) obj[k] = e = [];
e.push(v);
return e;
};
//
// Object utilities
//
/**
* Ensure an entry exists in a dictionary
*/
const getOrSet = (obj, k, v) => {
let e = obj[k];
if (!e) obj[k] = e = v;
return e;
};
/**
* Emptiness test
*/
const isNullOrEmpty = obj => {
if (obj === null || obj === undefined) return true;
const type = typeof obj;
if (type === "object") {
if (Array.isArray(obj)) {
return obj.length === 0;
}
return Object.keys(obj).length === 0;
}
if (type === "string") {
return obj === "";
}
return false;
};
//
// File utilities
//
/**
* Find all files inside a dir, recursively.
* @param {string} dir Dir path string.
* @return {string[]} Array with all file names that are inside the directory.
*/
const findAllFiles = dir =>
fs.readdirSync(dir).reduce((files, file) => {
const name = Path.join(dir, file);
const isDirectory = fs.statSync(name).isDirectory();
return isDirectory ? [...files, ...findAllFiles(name)] : [...files, name];
}, []);
/**
* Synchronously read an entire UTF-8 encoded file, stripping initial BOM
* code, if present
* @param {file} file
* @return {text}
*/
const readFile = file => {
if (!file) {
throw new Error("No file specifed for read");
}
let text = fs.readFileSync(file, "utf-8");
if (!text) {
throw new Error(`No text in file: ${file}`);
}
// Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
// conversion translates it to FEFF (UTF-16 BOM)
if (text.charCodeAt(0) === 0xfeff) {
text = text.slice(1);
}
return text;
};
const parseJSONFile = file => {
return JSON.parse(readFile(file));
};
module.exports = {
capitalize,
stripCRLF,
ellipse,
parseTime,
append,
getOrSet,
isNullOrEmpty,
findAllFiles,
readFile,
parseJSONFile
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment