Skip to content

Instantly share code, notes, and snippets.

View jonrandy's full-sized avatar
✴️
Sentient

Jon Randy jonrandy

✴️
Sentient
View GitHub Profile
@jonrandy
jonrandy / hashmod.html
Created April 8, 2025 06:45
HTML Hash Modules (self contained JS modules in an HTML file)
<!doctype html>
<html lang="en">
<body>
<script type="hash-module" id="sum">
export const sum = (a, b) => a + b;
</script>
<!-- All hash modules need to go before this script. -->
<!-- This cant be a type="module", it must be executed immediately. -->
<script>
@jonrandy
jonrandy / observePosition.js
Created June 11, 2024 03:21
Observe Position Changes of an HTML Element
export function observePosition(element, callback) {
const trackDiv = document.createElement("div")
Object.assign(trackDiv.style, {
position: "fixed",
pointerEvents: "none",
width: "2px",
height: "2px",
})
if (element.children.length) {
element.insertBefore(trackDiv, element.firstChild)
@jonrandy
jonrandy / arrayNegativeIndexProxy.js
Created May 31, 2024 11:22
Proxy an Array to allow negative indexes (like Array.at)
const arr = [1, 2, 3, 4]
const handler = {
get(target, prop, receiver) {
// try to convert property to a number
const n = +prop
// if it's a number less than zero, return the correct item from the array
if (!isNaN(n) && n<0) {
return Reflect.get(target, target.length + n, receiver)
// otherwise continue as normal with the property
@jonrandy
jonrandy / flagEmoji.js
Created May 22, 2024 03:39
Get Flag Emoji
// pass in 2 letter country code
const getFlagEmoji = countryCode=>String.fromCodePoint(...[...countryCode.toUpperCase()].map(x=>0x1f1a5+x.charCodeAt()))
const fib = n => {
const r5 = fib.r5 || (fib.r5=5**.5)
return Math.floor((((1+r5)/2)**n - ((1-r5)/2)**n)/r5)
}
@jonrandy
jonrandy / isPalindrome.js
Created October 31, 2023 08:34
isPalindrome
const isPalindrome = ([...s]) => ''+s == s.reverse()
function fibonacci(n) {
if (n < 0) throw RangeError("Negative arguments not implemented")
return fib(n)[0]
}
function fib(n) {
if (n) {
const [a, b] = fib(~~(n / 2)),
c = a * (b * 2n - a),
d = a * a + b * b
@jonrandy
jonrandy / nth_child.css
Created February 6, 2023 03:43
An nth-child CSS trick
:nth-child(1) { --nth-child: 1 }
:nth-child(2) { --nth-child: 2 }
:nth-child(3) { --nth-child: 3 }
:nth-child(4) { --nth-child: 4 }
:nth-child(5) { --nth-child: 5 }
/* ... */
* {
background-color: hsl(calc(100 * var(--nth-child)) 100% 40%);
}
@jonrandy
jonrandy / fisher.js
Last active July 16, 2024 08:29
Fisher Yates Shuffle
function shuffle(array) {
let a = [...array], m = a.length, i
while (m) {
// Pick a remaining element
i = ~~(Math.random() * m--);
// Swap it with the current element
[a[m], a[i]] = [a[i], a[m]]
}
return a
}
@jonrandy
jonrandy / carousel.html
Created November 15, 2022 02:48
Carousel without JS