Skip to content

Instantly share code, notes, and snippets.

View diegovgsilva95's full-sized avatar

Diego Silva diegovgsilva95

View GitHub Profile
@diegovgsilva95
diegovgsilva95 / index.mjs
Last active March 17, 2025 00:55
Node.js - Different permutation implementations: iterative buffer-based, iterative array-based and recursion-based
// A reasonably-efficient approach that uses "DMA" ("Direct Memory Access"), avoids multiple allocations (well, except for stack array) and (ab)uses mathematics
// In my tests, permutateBuffer is the fastest among the three.
const permutateBuffer = function(amount){
// It *should* work for browsers if Buffer is replaced with Uint8Array
if(isNaN(amount) || amount < 1 || amount > 10) // If you have sufficient memory and V8 is configured with enough heap, 10 can be increased
return Buffer.alloc(0)
let expected = 1
let carrier = 1
@diegovgsilva95
diegovgsilva95 / index.mjs
Created February 14, 2025 23:32
JS - Humanize and dehumanize byte-unit inputs (with support for both SI and binary byte prefixes)
// Note: I'm ignoring fractional bytes (e.g., 4.2 B is invalid input; 4.2 KiB or 4.2 KB are valid, tho ).
export const humanizeBytes = function(bytes, si = false, digits = 1){
let basis = si ? 1000 : 1024
let scale = (Math.log(Math.max(1,bytes)) / Math.log(basis))|0
let coeff = bytes / (basis ** scale)
let unit = scale == 0 ? "B" : ("KMGTP"[scale-1] + (si ? "" : "i") + "B")
return `${coeff.toFixed(scale == 0 ? 0 : digits)} ${unit}`
}
@diegovgsilva95
diegovgsilva95 / index.mjs
Created February 4, 2025 16:13
JS - Waiting for a specific datetime
async function waitUntilDatetime(timestamp, maxWait = 86400000) {
let beginAt = Date.now()
// Something scheduled should wait less than 24 hours, or 86400000 ms.
// After that point, it'll take too damn long, even for a daemon, so it should be refused.
if((timestamp - beginAt) > maxWait) // Refuse
throw new Error(`Requested to wait for ${timestamp - beginAt} ms., which exceeds the limit of ${maxWait} ms.`)
while(Date.now() < timestamp)
await sleep(Math.min(timestamp - Date.now(), 10000))
@diegovgsilva95
diegovgsilva95 / README.md
Created February 2, 2025 10:53
Node.js - Fair performance testing between two or more algorithms, or simply spawning isolated JS functions/code

Use cases

  • Spawning an isolated Node.js environment for running a given code
  • Accurately timing the execution of a given code (bypassing JIT optimizations which would lead to a biased timing)
  • Accurately comparing the timing between two or more algorithms (also, bypassing JIT optimizations which would lead to a biased timing)
@diegovgsilva95
diegovgsilva95 / index.mjs
Created January 29, 2025 03:52
Node.js - Parsing and sorting Pacman (Arch, btw) packages by decreasing size, together with their install reason (e.g., explicitly installed, installed as a dependency)
// Intended usage:
// $ pacman -Qi | node index.mjs
// I know there are (plenty of) existing solutions to this. I just made my own.
import { stdin, stdout } from "process"
import { Console, log } from "console"
import { createWriteStream, writeFileSync } from "fs"
import { writeFile } from "fs/promises"
const sleep = ms => new Promise(r => setTimeout(r, ms))
@diegovgsilva95
diegovgsilva95 / README.md
Created January 27, 2025 10:53
JS - Playing with randomness: mapping randomness unto itself and ranking the "best" surviving sequence

Purpose

Actually, none (do things really need to have a purpose?)... Just another tinkering with randomness.

What it Currently Does/Behaves

  1. Generates a list of random L numbers (currently 100 numbers).
  2. Maps the current list so every number (expectedly 0 <= n <= 1) becomes an index i (i = round(n × L)) pointing to the ith number in the current list.
  3. Calculates the current diversity (i.e., how many unique numbers survived from the last iteration).
  4. If diversity converges to less than 100 after a couple of runs, goes back to the step 1.
  5. If diversity converges to exactly 100 after a couple of runs, prints "Got the best of all!" and exits the loop.
  6. If diversity hasn't converged yet, goes back to the step 2.
@diegovgsilva95
diegovgsilva95 / README.md
Created January 6, 2025 02:12
JS - Splitting binary data into k-bit chunks (1<=k<=8)

test.mjs

Initial development of the bitwise approach, debugging and testing it against a lazy-man approach. Uses cli-table and chalk as dependencies for better visualization.

index.mjs

Refined and modularized code, containing just the bitwise approach as a function, followed by an invocation example.

Possible use-case scenarios

  • Base64 encoding/decoding
  • Perhaps experimentation with baudot code?
@diegovgsilva95
diegovgsilva95 / README.md
Last active January 4, 2025 23:16
Multiple scripting languages (JS, Python, Ruby): Code-golfing the base-64 encoding alphabet (just for fun)

Ruby

(0..63).map{|i|(((1+i/26)<<5)-i/52*81+i%26+i/62*(3*(i&1)-15)+33).chr}.join

The compactiest formula, with just 47 characters designed to calculate 64 characters. The entire one-liner has 74 characters.

Python

"".join([chr(((1+i//26)<<5)-(i//52*81)+i%26+(i//62*(3*(i&1)-15))+33) for i in range(0,64)])
@diegovgsilva95
diegovgsilva95 / index.mjs
Created December 11, 2024 02:15
JS + HTML: Snippet to create ASCII character table sprites
const canvas = document.querySelector("canvas")
const ctx = canvas.getContext("2d")
const table = await (await fetch("/data/8859-1.txt")).text() // Copied from Wikipedia's table
const idxTable = []
let idx = 0
for(let row of table.split("\n")){
for(let col of row.split("\t").slice(1)){
let uniChar = String.fromCharCode(idx)
if(uniChar != col)
@diegovgsilva95
diegovgsilva95 / index.mjs
Created December 10, 2024 07:06
JS - Math and Linguistics experimentation: calculating cyclic pattern from Gematria-like reduction from each English word for decimal digits
import {log} from "console"
const range = (n,x)=>Array.from(Array(Math.max(0,x-n+1))).map((_,i)=>i+n)
const numerals = "zero|one|two|three|four|five|six|seven|eight|nine".split("|")
const alpha = " "+String.fromCharCode(...range(96+1, 96+26))
for(let numeral of numerals){
let chain = [numeral]
let cycled = false