Skip to content

Instantly share code, notes, and snippets.

View DarrenSem's full-sized avatar

Darren Semotiuk DarrenSem

View GitHub Profile
@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 / UMD-javascript-module-template.js
Last active March 21, 2024 21:38
Universal Module Definition (UMD) template for JavaScript modules
// UMD-javascript-module-template.js
// Universal Module Definition (UMD) template for JavaScript modules
(function(root, factory) {
// var req1 = foo, req2 = bar; // or even exports
if(typeof exports === "object" && typeof module !== "undefined") {
module.exports = factory(req1, req2);
} else if(typeof define === "function" && define.amd) {
define([req1, req2], factory)
} else {
root["MOD_NAME"] = factory(req1, req2);
@DarrenSem
DarrenSem / Array.build.js
Last active December 1, 2023 20:53
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) ) - REPLACED BY Array.range.js
// REPLACED BY: Array.range.js => new Array( length, optionalEachFunction, optionalMapFunction )
// https://gist.github.com/DarrenSem/bc0403bcdad09912eb298e6d3b4824fe
// 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) )
Array.build ||= (length, callbackFn) => (
Array(length|0)
.fill(0)
@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 / 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 / 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 / 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 / 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 / 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 = {};