Skip to content

Instantly share code, notes, and snippets.

View DarrenSem's full-sized avatar

Darren Semotiuk DarrenSem

View GitHub Profile
@DarrenSem
DarrenSem / REPL.js
Last active January 16, 2023 16:45
REPL.js AKA eval.js -- Bookmarklet to append to current webpage a text input field + global-scope [EVAL] button - ALSO evaluates console.[log|error|warn|info|assert]
// REPL.js AKA eval.js -- REPL.js AKA eval.js -- Bookmarklet to append to current webpage a text input field + global-scope [EVAL] button - ALSO evaluates console.[log|error|warn|info|assert]
// javascript:void function(){var a=document,b=(b,c)=>Object.assign(a.createElement(b||"button"),c),c=b("pre"),d=b("div",{contentEditable:!0}),e="innerText",f=b(0,{[e]:"EVAL",onclick:(a,b,c,f=new Date().toLocaleTimeString(),g=location,h,i=/\bconsole\s*\.(log|error|warn|info|assert)\s*\(([^)])/g)=>{try{a=d[e],b=(g._=[],(i.test(a)?"let _=location,_log=(...a)=>{_._.push(a.join(\" \"));"+"\nlet m=(String(a[0]).match(/^<([aefgilnorw_ts]{3,6})>$/)||[])[1]||\"log\";console[m](...(a.slice(m==\"assert\"?1:0)))"+"\n};\n":"")+a).replace(i,`_log('<$1>', $2`),c=(0,eval)(b)+"",g._&&(c=g._.concat([c]).join("\n"))}catch(a){c=a.stack||a.message,c+="\n"+b}d[e]+=/[\n\r]/.test(c)?`\n\n/\* ${f}:\n${c.replace(/\*\//g,"* /")}\n*\/`:`\n// ${f}: ${c}`,d.focus()}});[f,c].forEach(({style:a},b)=>{a.border=b?"solid":"ridge",a.background=b?"#0aa":"#
@DarrenSem
DarrenSem / camelToKebab.js
Created January 24, 2023 17:42
camelCase convert to-kebab-case (or to_snake_case) -- camelToKebab(string, toSnakeNotKebab) -- also will recognize automatically when to call REVERSE function
// camelToKebab.js (string, toSnakeNotKebab) -- also will recognize automatically when to call REVERSE function
// 207 characters var camelToKebab=(a,b,c=/[_-]/.test(a))=>a&&a.link?a.replace(/\s/g,"").replace(/[A-Z_-]/g,c?" ":a=>" "+a).replace(/^\s+|\s+$/g,"").toLowerCase().replace(/ ([a-z]*)/g,c?a=>a.charAt(1).toUpperCase()+a.slice(2):b?"_$1":"-$1"):a
// /* // (to run JSCRIPT-compatible version, comment out arrow function)
var camelToKebab = (string, toSnakeNotKebab,
_reverse = /[_-]/.test(string)
) => (
@DarrenSem
DarrenSem / type.js AKA clazz constructor ctor.js
Created February 14, 2023 13:35
type.js AKA clazz constructor ctor.js (more granular than built-in typeof which returns "object" for most things)
// type.js AKA clazz constructor ctor.js (more granular than built-in typeof which returns "object" for most things)
// T=a=>({}).toString.call(a).slice(8,-1); // use case: if you have no need for JScript support
// T=function(a){return(null==a?a+"":{}.toString.call(a).slice(8,-1))}; // use case: non-JScript returns the same as JScript -- "null"/"undefined" instead of "Null"/"Undefined"
// T=function(a){return(/*@cc_on @if(@_jscript) null==a?a+"": @end@*/{}.toString.call(a).slice(8,-1))}; // use case: only JScript returns "null"/"undefined", while non-JScript returns "Null"/"Undefined"
var type = function(v) {
return (
/*@cc_on @if(@_jscript) v == null ? String(v) : @end@*/
{}.toString.call(v).slice(8,-1) // smaller than Object.prototype.toString.call(v).slice(8,-1)
@DarrenSem
DarrenSem / stringify.js
Last active February 14, 2023 14:48
stringify.js (handles virtually all types unlike the normal JSON.stringify -- intended for inspecting/displaying object values, NOT for serializing/exporting)
// stringify.js (handles virtually all types unlike the normal JSON.stringify -- intended for inspecting/displaying object values, NOT for serializing/exporting)
/*
this function's result is far more flexible, human-friendly, and USEFUL than JSON.stringify, because...
( Infinity ) => 'Infinity' and ( NaN ) => 'NaN' , instead of 'null'
( undefined ) => 'undefined' and ( Date ) => 'function Date() { [native code] }' , instead of undefined
( new TypeError("xyz") ) => 'TypeError: xyz' , instead of '{}'
( /z/img ) => '/z/gim' , instead of '{}' ( JSCRIPT => '/z/igm' )
( [ , ] ) => '[undefined]' , instead of '[null]'
@DarrenSem
DarrenSem / JSONstringify.js
Created February 15, 2023 19:02
JSONstringify.js - from-scratch implementation of JSON.stringify as a coding exercise ( and for JScript WSH using CSCRIPT.EXE /nologo MyJScript.js )
// JSONstringify.js - from-scratch implementation of JSON.stringify as a coding exercise ( and for JScript WSH using CSCRIPT.EXE /nologo MyJScript.js )
// 525 chars _=function(a){var b,c=null,d=typeof a,e=/^(undefined|function|bigint|symbol)$/i,f=0,g=[],h=function(a,b){return a==b?a+"":{}.toString.call(a).slice(8,-1)};if(!e.test(d)){if("string"===d)return"\""+a+"\"";if(!a||"object"!==d||"Number"===h(a))return("Number"===h(a)?isFinite(a)?+a:c:a)+"";if("Date"===h(a)&&!isNaN(a))return _(a.toISOString());if("Array"===h(a)){for(b=a.length;f<b;f++)g.push(_(e.test(h(a[f]))?c:a[f]));return"["+g+"]"}for(f in a)a.hasOwnProperty(f)&&!e.test(h(a[f]))&&g.push(_(f)+":"+_(a[f]));return"{"+g+"}"}}
var JSONstringify = function(obj) {
var NULL = null;
var type = typeof obj;
var skip = /^(undefined|function|bigint|symbol)$/i
var L;
var key = 0;
var elements = [];
@DarrenSem
DarrenSem / truncate.js
Created March 10, 2023 01:43
truncate.js (string, max) => "Ellipses after 1st half of ...then the second half of it." [2000 = default for max if omitted]
// truncate.js (string, max) => "Ellipses after 1st half of ...then the second half of it." [2000 = default for max if omitted]
// 101 chars:
// T=(a,b=2e3)=>null==a?"":(a=a+"").length>(b=Math.max(b,5))?a.slice(0,b/2-1)+"..."+a.slice(-b/2+1.5):a;
var truncate = (string, max = 2000) => (
string == null ? ""
: ( string = String(string) ).length > ( max = Math.max(max, 5) )
? (
string.slice(0, max / 2 - 1) + "..." + string.slice(-max / 2 + 1.5)
)
@DarrenSem
DarrenSem / negativeZero.js
Last active March 12, 2023 21:45
negativeZero.js - tiny JavaScript function to differentiate -0 from +0 (can process any type other than Symbol or BigInt)
// negativeZero.js - tiny JavaScript function to differentiate -0 from +0 (can process any type other than Symbol or BigInt)
// 15 chars: N=a=>1/0==1/-a;
var negativeZero = v => Infinity === 1 / -v; // => v === 0 && Number.NEGATIVE_INFINITY === 1 / v;
var isWeb = Date.now; // JScript is missing this method
var values = [
@DarrenSem
DarrenSem / process.js-for-HackerRank.js.md
Last active June 15, 2023 19:49
process.js-for-HackerRank

process.js-for-HackerRank

#nodejs #polyfill #browser #hackerrank #node-js #client-side #hackerrank-solutions #hackerrank-javascript #hackerrank-30dayschallange #hackerrank-challenges

https://github.com/DarrenSem/process.js-for-HackerRank (might have more recent updates/improvements)

Minimal polyfill (324 characters minified) for client-side JS to add missing NodeJS functions for completing HackerRank.com challenges -- process.stdin/stdout/env.OUTPUT_PATH and require("fs").createWriteStream

(So I can complete HackerRank.com challenges on my cell using my custom REPL bookmarklet.)

@DarrenSem
DarrenSem / hostnameRoot.js
Created September 25, 2023 11:22
hostnameRoot.js -- returns URL/location.hostname with certain prefixes removed: m. mob. mobi. mobile. www. www[0-9]. ww[0-9].
// hostnameRoot.js -- returns URL/location.hostname with certain prefixes removed: m. mob. mobi. mobile. www. www[0-9]. ww[0-9].
const hostnameRoot = hostname => String(hostname ?? "")
.toLowerCase()
.replace(
/^(m(ob(i(le)?)?)?|ww(w?\d|w))\.(.+?\..+)/,
"$6"
);
console.log([
@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.