Skip to content

Instantly share code, notes, and snippets.

@mayank99
mayank99 / inline-workers.js
Last active May 6, 2024 10:44
Create a web worker in the same file where it's used
function createWorker(fn) {
const url = URL.createObjectURL(
new Blob([`\
onmessage = ({ data }) => {
const fn = ${fn.toString()};
const result = fn(...JSON.parse(data));
self.postMessage(result);
};
`])
);
@mayank99
mayank99 / importCss.js
Created December 12, 2023 04:29
import attributes polyfill
async function importCss(url) {
try {
return await (new Function(`return import("${url}", { with: { type: "css" } })`))();
} catch {
try {
return await (new Function(`return import("${url}", { assert: { type: "css" } })`))();
} catch {
return fetch(url).then(res => res.text()).then(cssText => {
const stylesheet = new CSSStyleSheet();
@mayank99
mayank99 / $.js
Last active May 6, 2024 10:44
make your own `execa`-like shell with node built-ins
import { promisify } from 'node:util';
import { exec } from 'node:child_process';
const $ = async (strings, ...values) => {
try {
return (await promisify(exec)(String.raw({ raw: strings }, ...values))).stdout;
} catch {
return ''; // yolo
}
};
@mayank99
mayank99 / mulberry.ts
Created March 25, 2022 23:23
A very simple mulberry cipher
const chars = [...'0123456789abcdefghijklmnopqrstuvwxyz'];
const charsMap = Object.fromEntries(chars.map((letter, i) => [letter, i]));
/**
* Function that encodes a string using mulberry32.
* @param what What do you want to encode?
* @param seed Pick a seed, any seed.
* @returns Encoded string.
*/
export const encode = (what: string, seed: number) => {