Skip to content

Instantly share code, notes, and snippets.

View DarrenSem's full-sized avatar

Darren Semotiuk DarrenSem

View GitHub Profile
@DarrenSem
DarrenSem / Math.sum [ , Math.avg , Math.max , Math.sum ] .js
Created November 24, 2022 18:06
Math.sum.js and Math.avg (average) and Math.max and Math.sum -- ALL will automatically flatten (all, args, passed, [[even, [, Arrays]]])
// Math.sum.js and Math.avg and Math.max and Math.sum -- ALL will automatically flatten (all, args, passed, [[even, [, Arrays]]])
console.log(Math.sum);
// undefined
console.log(Math.avg);
// undefined
console.log(Math.max);
// ƒ max() { [native code] }
@DarrenSem
DarrenSem / randomWithSeed.js
Last active December 21, 2023 18:07
randomWithSeed.js - use rnd() after rnd = createRandomWithSeed( seed [0+] = Date.now() ) - Math.random is less than 2x faster than this 'good enough' SEED-able version
// randomWithSeed.js - use rnd() after rnd = createRandomWithSeed( seed [0+] = Date.now() ) - Math.random is less than 2x faster than this 'good enough' SEED-able version
let createRandomWithSeed = seed => {
seed = Math.abs(isNaN(seed) ? Date.now() : seed);
return () => {
seed = (seed * 9301 + 49297) % 233280;
return seed / 233280;
};
};
// R=s=>(s=Math.abs(isNaN(s)?Date.now():s),_=>(s=(9301*s+49297)%233280,s/233280));
@DarrenSem
DarrenSem / innerText.js
Last active January 26, 2025 18:33
innerText.js bookmarklet for mobile (to show webpage text contents OR html) (including PARTIAL source of SELECTION)
// innerText.js bookmarklet for mobile (to show webpage text contents OR html) (including PARTIAL source of SELECTION)
// https://gist.github.com/DarrenSem/7e1216bda80e6269ad53b43d90603158
// 26Jan2025 BUGFIX: now missing ONLY the "System instructions" section (one extra div layer was added SIGH)
// 4784 char javascript:void function(){"use strict";const e="main div[data-collapsed",n="engine-select",t=`div.model-select>button>span`,d=[]._,i=((e,t,i,a,n,l,d,r)=>(t=new Date(e||Date()),[i,a,,n]=t.toLocaleTimeString().replace(/(a|p)\.(m)\./i,"$1$2").split(/\W/),[,,l,d]=t.toString().split(" "),r=t.toLocaleString().replace(/(\d+)-(\d+)-(\d+)/,"$2/$1/$3").split("/")[0].padStart(2,0),`${i}${a}${(n||"").toLowerCase()} ${d}-${r}-${l}`))(),a=`${""} ${i}`,l=top.document,r=location,u=(e,n)=>(n||l).querySelectorAll(e||null),o=(e,n)=>{const t=e?.[n?"value":x],i=t==d?d:n?t:t.replace(/\n{3,}/g,"\n\n\n").replace(/\n\n/g,"\n");return i},f=e=>e.trim(),s=e=>(e??"").replace(/\nSYNC$/i,"").replace(/ INSTRUCTIONS$/i,""),c=e=>(e??
@DarrenSem
DarrenSem / contentsInNewWindow.js
Last active October 15, 2023 17:28
OpenInNewWindow(data, type) - F5-REFRESHABLE! - auto-UTF8 if type==="text"! - also ContentsInNewWindow(contents = '' or [], Title, type, delimToJoinArray = "\n\n")
// contentsInNewWindow.js - F5-REFRESHABLE! - with TITLE! - (contents = '' or [], title, type = 'octet-stream', array-joining-delim = '\n\n')
// const contentsInNewWindow=(c=[],T,t="octet-stream",d="\n\n")=>{const w=open(URL.createObjectURL(new Blob([[c].flat(1/0).join(d)],{type:"text"===t?t+"/plain;charset=utf-8":t})),"_blank");return w&&!w.closed&&(w.onload=()=>w.document.title=T),w};
const contentsInNewWindow = (contents = [], title, type = ["text", "octet-stream"][1], delim = "\n\n") => {
const win = open(
URL.createObjectURL(
new Blob([
[contents].flat(1/0).join(delim)
], {
// auto-UTF8 if type === 'text', to easily ensure visible emojis etc.
@DarrenSem
DarrenSem / shuffle.js
Created November 12, 2022 04:25
shuffle.js - fastest possible after countless speed comparisons - minified to 76 characters
// shuffle.js
// minified = 76 chars (not including 'R=Math.random') s=a=>{for(let b,c,d=a.length-1;0<d;)b=0|R()*(d+1),c=a[d],a[d--]=a[b],a[b]=c}
// after doing console.time speed comparisons of Every. Possible. Version and logic permutation I could find:
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
// https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
// https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
// pre-cached "R" faster because no OBJECT.KEY lookup each time
let R = Math.random;
@DarrenSem
DarrenSem / dtString.js
Created November 6, 2022 20:02
dtString.js (dateArg, includeTime, defaultDate, defaultReturnValue) '1-2-2022 1:00' returns '02Jan2022 100am' or '02Jan2022'
// dtString.js (dateArg, includeTime, defaultDate, defaultReturnValue) '1-2-2022 1:00' returns '02Jan2022 100am' or '02Jan2022'
const assert=(...a)=>!a.reduce((b,c,d,e,f)=>(f=("function"==typeof c?!c():!c)&&[2>a.length?c:`<arg #${d+1}> ${a.map((a,b)=>`#${b+1} = [ ${a} ]`).join(" , ")}`],f&&console.assert(0,...b[b.push(f)-1]),b),a.length?[]:[a]).length;
const assertMessage = (test, ...messageAndSubstitutions) => assert(test) || console.error(...messageAndSubstitutions) || false;
console.clear();
// 183 chars: const dtString=(a,b,c,e,f=new Date(a),[,,,,g,h,,i]=(f=+f?f:new Date(c)).toLocaleString().toLowerCase().split(/\W/),[,j,k,d]=f.toString().split(" "))=>isNaN(f)?e:`${k}${j}${d}${b?` ${g}${h}${i}`:""}`
const dtString = (dateArg, includeTime, defaultDate, defaultReturnValue, z = new Date(dateArg), [, , , , h, n, , ampm] = (z = +z ? z : new Date(defaultDate)).toLocaleString().toLowerCase().split(/\W/), [, m, d, y] = z.toString().split(" ")) => isNaN(z) ? defaultReturnValue : `${d}${m}${y}${includeTime ? `
@DarrenSem
DarrenSem / download.js
Last active November 18, 2022 00:09
download.js: SAVE data TO file (aka 'export/download') plus openInNewWindow(data, type = "octet-stream")
/////// download.js: SAVE data TO file (aka 'export/download')...
//// const download_MIN=(d,f=`file-${+new Date}.txt`,t="octet-stream")=>{const h=URL.createObjectURL(new Blob([d].slice(void 0===d),{type:t})),s=null!==f;return Object.assign(document.createElement("a"),{href:h,[s&&"download"]:f,target:"_blank"}).click(),s&&URL.revokeObjectURL(h)};
const download = (
data
, filename = `file-${+new Date}.txt` // null means download: filename OMITTED = DISPLAY data in browser
, type = "octet-stream" // default is ~ "application/octet-binary"
) => {
const href = URL.createObjectURL(new Blob( // https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
[data].slice(data === undefined)
@DarrenSem
DarrenSem / replaced(original, pattern1, replacement1, patternX, replacementX).js
Created August 8, 2022 19:59
replaced(original, pattern1, replacement1, patternX, replacementX).js - enables MULTIPLE PAIRS in a single call - very flexible syntax e.g. replaced(original, ["pattern(number)1", "replacement$1"], /p2/, "r2", "p3", "r3")
// replaced(original, pattern1, replacement1, patternX, replacementX).js - enables MULTIPLE PAIRS in a single call - very flexible syntax e.g. replaced(original, ["pattern(number)1", "replacement$1"], /p2/, "r2", "p3", "r3")
var replaced = (p, ...pairsFindReplacewith) => pairsFindReplacewith.flat(Infinity).reduce(
(curr, string, i) =>
i % 2 ? curr.replace(p, string)
: (p = RegExp(string, "g"), curr)
, String(p != null ? p : "") // AKA String(p ?? "") // p != null ? String(p) : ""
)
@DarrenSem
DarrenSem / ordinal.js
Created July 10, 2022 21:41
ordinal.js - one-liner returns ordinal(1)="1st", (2)="2nd", (3)="3rd", (11)="11th", (21)="21st", (111)="111th", (121)="121st", etc.
// ordinal.js - one-liner returns ordinal(1)="1st", (2)="2nd", (3)="3rd", (11)="11th", (21)="21st", (111)="111th", (121)="121st", etc.
let ordinal = num => `${num}${[, "st", "nd", "rd"][ (num % 100 < 11 || num % 100 > 13) && (num % 10) ] || "th"}`;
// ^ Final Answer. (below = the story of how I got there...)
"use strict";// ordinal.js - one-liner returns ordinal(1)="1st", (2)="2nd", (3)="3rd", (11)="11th", (21)="21st", (111)="111th", (121)="121st", etc.
let ordinal = num => `${num}${[, "st", "nd", "rd"][ (num % 100 < 11 || num % 100 > 13) && (num % 10) ] || "th"}`;
@anuraghazra
anuraghazra / minimal-templating-engine.ts
Last active August 2, 2024 09:48
Minimal Templating Engine In Javascript
// magic!
function dom<Props extends Record<string, unknown>>(
str: TemplateStringsArray,
...args: string[] | ((props: Props) => string)[]
) {
const interleaved = args.flatMap((arg, index) => {
return [arg, str[index + 1]];
});
return (props?: Props) =>