Skip to content

Instantly share code, notes, and snippets.

View DarrenSem's full-sized avatar

Darren Semotiuk DarrenSem

View GitHub Profile
@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 / upload.js
Created October 31, 2022 18:01
upload.js: LOAD data FROM files (aka 'import/upload') including handling drag-and-drop
/////// upload.js: LOAD data FROM files (aka 'import/upload')...
// const buildFileSelector=(a,m)=>{const c=null==a?"":a+"";return Object.assign(document.createElement("input"),{type:"file"},m&&{multiple:m},c.trim().length&&{accept:c})};
// const resetFileSelector=e=>e&&(e.value=null,e);
// const getFileSelector=(e,c,a,m,r)=>resetFileSelector(e)&&e.readAs===r?e:Object.assign(e||buildFileSelector(a,m),{onchange:c,readAs:r});
// SEE BELOW: handleUploadOrDropExample = event => {
// Warning: "File chooser dialog can only be shown with a user activation." (just like clipboard functionality)
// const buildFileSelector=(a,m)=>{const c=null==a?"":a+"";return Object.assign(document.createElement("input"),{type:"file"},m&&{multiple:m},c.trim().length&&{accept:c})};
@DarrenSem
DarrenSem / filledArray(n, funcForEachIndex).js
Last active December 1, 2023 20:53
filledArray.js - create a new array of size 'n' filled with values that result from calls to funcForEachIndex(index) - REPLACED BY: Array.range.js
// REPLACED BY: Array.range.js => new Array( length, optionalEachFunction, optionalMapFunction )
// https://gist.github.com/DarrenSem/bc0403bcdad09912eb298e6d3b4824fe
// previously REPLACED BY: Array.build.js -- sugar for functional equivalent of new Array( length, functionUsingIndex ) aka fillArray(L, F) -- returns Array(length).fill(0).map( (_, i) => callbackFn(i) )
// https://gist.github.com/DarrenSem/bf49d0c87083301a88111b5d444f0a5f
@DarrenSem
DarrenSem / bufferToHexString.js
Last active October 31, 2022 13:52
bufferToHexString.js (and stringsToBuffer and stringFromCharCodeArray)
// bufferToHexString and stringsToBuffer and stringFromCharCodeArray.js
const bufferToHexString = (arraybuffer, delim = "\t", z = "0123456789abcdef") => [...new Uint8Array(arraybuffer)].map(v => z[v >> 4] + z[v & 15]).join(delim);
const bufferToHex_clearest = (arraybuffer, delim = "\t") => [...new Uint8Array(arraybuffer)].map(v => v.toString(16).padStart(2, "0")).join(delim); // .toString(16).padStart = more clear even if slower than using pre-computed HEX[0..255] https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex/55200387#55200387
const bufferToHex_reduce_instead_of_map = arraybuffer => [...new Uint8Array(arraybuffer)].reduce((acc, v) => acc + v.toString(16).padStart(2, "0"), ""); // reduce instead of map because "map is reimplemented for typed arrays to return a typed array for each element, instead of a Uint8" // https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex/70790307#70790307
const HEX = new Array(0xff); for (let i = 0; i <= 0xff; i++)HEX[i] = i.toSt
@DarrenSem
DarrenSem / globalThis-tests.js
Created October 30, 2022 23:14
globalThis-tests.js -- everything you ever wondered about globalThis (and possible polyfills) but never thought to ask
// globalThis-tests.js -- everything you ever wondered about globalThis (and possible polyfills) but never thought to ask
// console.clear();
console.log("\nglobalThis-tests.JS\t", new Date());
/////// no pre-setup (typical one-time kind of usage)
// (function (glo) { glo._var_$ = 7; })(typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : this || {}); // .mjs needed additional || {} ... otherwise imo this is a #GoodEnough compromise (and much more clear!) compared to O_O https://mathiasbynens.be/notes/globalthis
// console.log("\n? (preferred way) globalThis._var_$ set by calling IIFE, confirm it was set to 7:\t", globalThis._var_$, "\n");
@DarrenSem
DarrenSem / blobFromDataUrl.js
Created October 29, 2022 18:49
blobFromDataUrl.js and binaryFromDataUrl_RESEARCH (multiple ways including fetch and Uint8Array.from)
/////// binaryFromDataUrl_RESEARCH (multiple ways including fetch and Uint8Array.from).js
// const blobFromDataUrl=(d,z)=>(z=d.match(/^data:(.*?)(?:;base64)?,(.*)/),new Blob([Uint8Array.from(atob(z[2]),a=>a.charCodeAt(0))],{type:z[1]||"octet-stream"}));
// async function binaryFromDataUrl_RESEARCH(src) { // blobOrArrayBufferOrTypedArray = await binaryFromDataUrl_RESEARCH(dataUrl);
const binaryFromDataUrl_RESEARCH = async src => { // blobOrArrayBufferOrTypedArray = await binaryFromDataUrl_RESEARCH(dataUrl);
// src = "data:[<media type>][;base64],<data>" via https://en.wikipedia.org/wiki/Data_URI_scheme#Syntax
// const base64String = src.slice(src.indexOf(",") + 1); // const base64String = src.split(",", 2)[1]
@DarrenSem
DarrenSem / imageFromDataUrl.js
Created October 29, 2022 18:48
imageFromDataUrl.js (src, callback) and blobFromDataUrl.js (dataUrl)
/////// imageFromDataUrl.js (src, callback) and blobFromDataUrl.js (dataUrl)
// const imageFromDataUrl=(a,b)=>Object.assign(document.createElement("img"),{src:a,onload:b||function(a,b){console.log([`Image loaded (${(b=a.target).width} x ${b.height})\n${new Date}`,this])}});
const imageFromDataUrl = (src, callback) => (
Object.assign(document.createElement("img"), { // or Object.assign(new Image(), ...
src
, onload: callback || function (event, z) {
console.log([`Image loaded (${(z = event.target).width} x ${z.height})\n${new Date}`, this]);
}
})
@DarrenSem
DarrenSem / openInNewWindow.js.md
Last active November 27, 2022 20:57
openInNewWindow.js: DISPLAY data in new (and REFRESHABLE!) tab/window -- (data, type = "octet-stream")
@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)