Skip to content

Instantly share code, notes, and snippets.

View DarrenSem's full-sized avatar

Darren Semotiuk DarrenSem

View GitHub Profile
@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 / 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 / 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 / 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 / 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 / require.js
Created December 28, 2022 21:14
require.js in just 793 chars -- even works from local CSCRIPT.EXE JScript.js (because not everybody runs Node) -- var exports = require('moduleName')
// require.js in just 793 chars -- even works from local CSCRIPT.EXE JScript.js (because not everybody runs Node) -- var exports = require('moduleName')
(function(a){var b={},c=[],d=function(a,d){var f={exports:{}},g=a.length?e.resolve(a,c[0]):"",h=e.fetch(g),i=null!=h&&eval("[(function(exports,require,module,__filename,__dirname){"+(h+"})][0]"));if(i){b[d]=f.exports,c.unshift(g);try{i(b[d],e,f,g,e.dir(g))}catch(a){}return c.shift(),f.exports}},e=function(a){var c=(a+"").replace(/\\/g,"/").replace(/\.js$/i,""),e=c.toLowerCase();if(a)return e in b?b[e]:d(c,e)};e.resolve=function(a,b){return(/^\.{1,2}/.test(a)?e.dir(b||location.href.replace(/\\/g,"/"))+"/":"")+a+".js"},e.fetch=function(a){try{var b=a.length&&new XMLHttpRequest,c=b&&(b.send(b.open("GET",a,!1)),b.status),d=b&&b.responseText;if(200===c||d.length&&!c)return d}catch(a){}},e.dir=function(a){var b=a.lastIndexOf("/");return 0>b?"":a.slice(0,b)},a.require=a.require||e})(this);
(function(globalContext){
var moduleName = "require";
var cache = {};
@DarrenSem
DarrenSem / xt.js
Last active December 28, 2022 07:10
xt.js
console.log("TOP");
exports.importedInfo = [, 3, 6, 9, exports && exports.length, "someGlobal:", typeof someGlobal !== "undefined" && someGlobal];
module.exports.xyz = 123;
alert('executing xt.js?' + location.href);
@DarrenSem
DarrenSem / HTML.js
Created December 1, 2022 01:15
HTML.js - display full webpage source (document.documentElement.outerHTML) into a new tab popup
// HTML.js - display full webpage source (document.documentElement.outerHTML) into a new tab popup
// RUN = 304 char: javascript:void function(){let a=open("about:blank").document,b=a.body;b.appendChild(a.createElement("b")).innerText=a.title=`Source code of ${location.href}`;let c=b.appendChild(a.createElement("pre"));c.innerText=document.documentElement.outerHTML,c.style.whiteSpace="pre-wrap",c.style.color="blue"}();
let doc = open('about:blank').document;
let body = doc.body;
let tagForTitle = "b";
body.appendChild(doc.createElement(tagForTitle)).innerText = doc.title = `Source code of ${location.href}`;
@DarrenSem
DarrenSem / selectedHtml.js
Last active November 30, 2022 20:00
selectedHtml.js -- returns [htmlString, htmlString.length] , args are ALL optional ( doc, selection = doc.getSelection(), range = selection.getRangeAt(0) )
// selectedHtml.js -- returns [htmlString, htmlString.length] , args are ALL optional ( doc, selection = doc.getSelection(), range = selection.getRangeAt(0) )
// const selectedHtml=(b=document,c=b.getSelection(),d=c&&c.getRangeAt(0),e=d&&a.createElement("div"),f=e?(e.appendChild(d.cloneContents()),e.innerHTML):"")=>[f,f.length];
const selectedHtml = (
_doc = document,
_sel = _doc.getSelection(), // "You can call Window.getSelection(), which works identically to Document.getSelection()." https://developer.mozilla.org/en-US/docs/Web/API/Document/getSelection
_range = _sel && _sel.getRangeAt(0),
_el = _range && doc.createElement("div"),
_result = !_el ? "" : (
@DarrenSem
DarrenSem / htmlDecode.js
Created November 29, 2022 18:28
htmlDecode.js htmlEncode.js - using modern browsers' built-in DOM manipulation (plus common escaping for htmlEncode)
// htmlDecode.js htmlEncode.js - using modern browsers' built-in DOM manipulation (plus common escaping for htmlEncode)
// let htmlDecode=a=>Object.assign(document.createElement("textarea"),{innerHTML:null==a?"":a.replace(/<\s*br\s*\/?\s*>/gi,"\n")}).value;
let htmlDecode = html => Object.assign(
document.createElement("textarea"), {
innerHTML: html == null ? "" : html.replace(/<\s*br\s*\/?\s*>/gi, "\n")
}
).value;
// let htmlEncode=a=>Object.assign(document.createElement("div"),{innerText:null==a?"":a}).innerHTML.replace(/<br>/g,"\n").replace(/['"\t\f\r\n\u00A0-\u2666]/g,a=>({"'":"&#039;",'"':"&quot;"})[a]||`&#${a.charCodeAt(0)};`);