Skip to content

Instantly share code, notes, and snippets.

View JosePedroDias's full-sized avatar

José Pedro Dias JosePedroDias

View GitHub Profile
@JosePedroDias
JosePedroDias / generic_export_recipe.js
Last active February 11, 2024 23:06
recipe to expose a JS module for CommonJS, AMD and global namespace
(function(context) {
'use strict';
var modName = 'stuff'; // used only if mod is a function and no CommonJS or AMD supported
// define your module here... can be a function or an object
var mod = {};
// export
if (typeof module === 'object' && module.exports) { // CommonJS
@JosePedroDias
JosePedroDias / weightedRandom.mjs
Created December 2, 2023 19:08
returns random outcomes based on a configuration of their weights
// array of [outcome, weight]
export function weightedRandom(arr) {
const outcomeCuts = [];
let accum = 0;
for (const [out, weight] of arr) {
accum += weight;
outcomeCuts.push([out, accum]);
}
const r = accum * Math.random();
let best;
@JosePedroDias
JosePedroDias / AesCbc.ts
Last active October 31, 2023 11:55
AES CBC friendly impl using subtle crypto for both nodejs and the browser
// import { webcrypto as crypto } from 'node:crypto'; // NODE
// eslint-disable-next-line no-undef
const crypto = globalThis.crypto; // BROWSER
const subtle = crypto.subtle;
const ALGO = 'AES-CBC';
// HELPER FUNCTIONS
@JosePedroDias
JosePedroDias / produce_consume.ts
Created October 20, 2023 09:22
multiple consumers of a promise
function defer<T>(): {
promise: Promise<T>;
resolve: (resp: T) => void;
reject: (err: any) => void;
} {
const answer: any = {};
answer.promise = new Promise((resolve, reject) => {
answer.resolve = resolve;
answer.reject = reject;
});
@JosePedroDias
JosePedroDias / stacklang.mjs
Last active October 14, 2023 00:51
simplest stack calculator
import { test } from 'node:test';
import { strictEqual, deepEqual } from 'node:assert';
/*
inspired by https://www.youtube.com/watch?v=umSuLpjFUf8
3 3 * 4 4 * + sqrt
equivalent to
Math.sqrt(3*3 + 4*4)
*/
@JosePedroDias
JosePedroDias / spy.ts
Last active September 27, 2023 15:36
spies of method calls and optionally returns prepared results instead
export function spy(fn: Function, prot = fn.prototype) {
function proxyFn() {
const args = Array.prototype.slice.call(arguments);
const call = { args, result: undefined, error: undefined, real: true };
proxyFn.calls.push(call);
let responded = false;
// check if preparedCalls can answer
@JosePedroDias
JosePedroDias / fetchFireAndForget.ts
Created December 3, 2020 16:24
fetch fire and forget in nodejs (I suppose it works in the browser as well)
import http from 'http';
import https from 'https';
import fetch, { Response } from 'node-fetch';
import { AbortController } from 'abort-controller';
const DEFAULT_TIMEOUT = 10000;
const httpAgent = new http.Agent({
keepAlive: true,
@JosePedroDias
JosePedroDias / streamLines.mjs
Created September 15, 2023 17:12
streams a non-binary file avoiding loading it all to memory
import { createReadStream } from 'fs';
export function streamSplitBy(file, onMatch, splitBy='\n') {
return new Promise((resolve) => {
const stream = createReadStream(file);
let ongoing = '';
stream.on('data', buff => {
const chunk = buff.toString();
type SortableType = number | string | boolean;
type SortFn<T> = (el: T) => SortableType;
interface SortHelperApi<T> {
sortBy(fn: SortFn<T>, decrescent?: boolean): SortHelperApi<T>;
execute(): T[];
}
/**
@JosePedroDias
JosePedroDias / cors.py
Created February 20, 2018 00:50
mitmproxy CORS
# based on https://gist.github.com/jhass/652dd780d23c1e236ff913e8a2b77eb2
# http://jsbin.com/wonitaqode/edit?js,output
# mitmproxy -s cors.py
# mitmdump -s cors.py
from mitmproxy import http
def response(flow):
h = flow.request.headers