Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
crazy4groovy / try-it.js
Created May 28, 2021
"most productive" exception handling ever (JavaScript)
View try-it.js
try {
// something that might go wrong...
} catch (e) {
var url = 'https://stackoverflow.com/search?q=[js]+' + e.message;
window.open(url, '_blank');
}
@crazy4groovy
crazy4groovy / deps-proxy-lazy.js
Last active Jul 19, 2021
A concept of using ESModule dynamic imports to reduce the js bundle size (i.e. only download the libs you use, at runtime!). (Deno) (NodeJS)
View deps-proxy-lazy.js
// see: https://gist.githubusercontent.com/crazy4groovy/0320e065af1cc1d070679293521d6320/raw/idle-exec.js
// function idleExec(fn) { ... }
// idleExec is probably overkill for prime, setTimeout is simple!
import { _ } from "./deps-proxy.js";
idleExec(() => _.get); // prime the cache, async
idleExec(() => _.has); // prime the cache, async
setTimeout(() => _.get, 1); // prime the cache, async
@crazy4groovy
crazy4groovy / question.js
Last active May 28, 2021
cli read line / ask question / user input (NodeJS)
View question.js
// https://github.com/google/zx/blob/1508858ae964e49e0e5667860f7075b2a6aa15bf/index.mjs#L94
import {createInterface} from 'linebyline'
export async function question(query, options) {
let completer
if (Array.isArray(options?.choices)) {
completer = function completer(line) {
const completions = options.choices
const hits = completions.filter((c) => c.startsWith(line))
return [hits.length ? hits : completions, line]
@crazy4groovy
crazy4groovy / range-list.js
Last active Jul 21, 2021
Generator function to iterate over a set of numbers, or create an array of numbers; matches python's native `range` and `list` functions (JavaScript) (Deno)
View range-list.js
// ES Module: import { range, list } from 'https://gist.githubusercontent.com/crazy4groovy/4d871aadad1d71754a863e92f119c489/raw/range-list.js'
// function range(begin: number?, end: number?, inc: number?) => Generator<number>
export function* range(b = 0, e, i = 1) {
if (e === undefined) {
// shift args
e = b;
b = 0;
}
// handle -ve inc
@crazy4groovy
crazy4groovy / args.ts
Last active Apr 23, 2021
Runs a given command for each file in a folder, recursively; replaces #FILE_PATH, #FILE_NAME, #FILE_SIZE_KB in command (Deno)
View args.ts
import * as fs from "https://deno.land/std@0.93.0/fs/mod.ts";
import * as path from "https://deno.land/std@0.93.0/path/mod.ts";
export default () => {
let [execCmdTemplate, basedir = ".", fileExt = ""] = Deno.args;
if (!execCmdTemplate) throw new Error("No command was given");
if (!basedir || !fs.existsSync(basedir)) throw new Error("DIR doesn't exist");
basedir = path.resolve(".", basedir);
return { execCmdTemplate, basedir, fileExt };
}
@crazy4groovy
crazy4groovy / dl.ts
Last active Apr 19, 2021
dl images from cdn (Deno)
View dl.ts
import { Timeout, TimeoutError } from "https://deno.land/x/timeout/mod.ts"
export default async function download(
source: string,
destination: string
): Promise<boolean> {
try {
const req = fetch(source);
const response = await Timeout.race([req], 5000);
const blob = await response.blob();
@crazy4groovy
crazy4groovy / fetcher.js
Last active Apr 6, 2021
Simple web page html parser into markdown or JSON (NodeJS)
View fetcher.js
const fetch = require('node-fetch')
module.exports = async ({q, url}) =>
fetch(
url
? decodeURIComponent(url)
: `https://en.wikipedia.org/wiki/${decodeURIComponent(q)}`
).then(res => res.text())
@crazy4groovy
crazy4groovy / fetch-file.js
Last active Apr 7, 2021
fetch / download a URL / binary file (NodeJS)
View fetch-file.js
const fs = require("fs");
const fetch = require("node-fetch");
function dl(url, destFilename) {
return new Promise((resolve, reject) => {
fetch(url).then((res) => {
res.body.pipe(fs.createWriteStream(destFilename))
res.body.on('end', resolve)
res.body.on('error', reject)
}).catch(reject)
@crazy4groovy
crazy4groovy / file-logger.js
Last active Mar 26, 2021
simple file logger (NodeJS)
View file-logger.js
const newFileLogger = (filename, init = false) => {
if (init) fs.writeFileSync(filename, '', 'utf8'); // wipe/reset
return (...lines) => {
fs.appendFileSync(
filename,
lines
.map(l => JSON.stringify(l, null, 2))
.join('\n') + '\n',
'utf8'
)
@crazy4groovy
crazy4groovy / by-line-lib.js
Last active Apr 1, 2021
Stream: a large text file line-by-line; dir recursively (NodeJS)
View by-line-lib.js
const fs = require("fs");
const readline = require("readline");
const byLine = async ({file, handleLine, charset="utf8"}) => {
return new Promise((done, err) => {
if (!fs.existsSync(file)) {
return err(new Error('File not found!'));
}
const rl = readline.createInterface({
input: fs.createReadStream(file, charset),