Skip to content

Instantly share code, notes, and snippets.

View DarrenSem's full-sized avatar

Darren Semotiuk DarrenSem

View GitHub Profile
@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 / 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 / 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 / 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 / ytSubs.js
Last active March 26, 2024 20:28
ytSubs.js - YouTube subtitles - English (auto-generated) CC (closed captions) - Usage: node ytSubs.js videoIdOrUrl, or Web browser BOOKMARKLET into a new window
// ytSubs.js (SEE DISCLAIMER) - via @DarrenSem https://gist.github.com/DarrenSem (22Mar2024)
// YouTube subtitles - English (auto-generated) CC (closed captions)
// Usage: node ytSubs.js videoIdOrUrl
// or Web browser BOOKMARKLET (contents open in a new window)
// ES6 bookmarklet = 4045 chars
javascript:void function(){"use strict";var a=String.fromCharCode;const b="",c=async a=>{try{if(globalThis.fetch){const b=await fetch(a),c=await b.text();return c}return new Promise((b,c)=>{const d=require(/^https/.test(a)?"https":"http").get(a,d=>{if(200>d.statusCode||299<d.statusCode)return c(Error(`${d.statusCode} ${d.statusMessage} ${a}`));const e=[];d.on("data",a=>e.push(a)),d.on("end",()=>b(e.join("")))});d.on("error",a=>c(a))})}catch(a){throw a}},d=a=>{try{a=(a||"")+"";const b=a.match(/"captionTracks":.*"isTranslatable"\:.*?}]/),c=JSON.parse(`{${(b||[""])[0]}}`).captionTracks||[],d=c.map(a=>{const b=a.name;return[g(b.simpleText||b.runs&&b.runs[0].text),a.baseUrl+"&fmt=json3"]});return d}catch(a){}},e=(a,b,c,d)=
@DarrenSem
DarrenSem / mongodb-getDocumentArray.js
Last active November 2, 2023 22:12
MongoDB - function getDocumentArray( fnEachDocument, ...documents ) - returns cloned Array of passed documents (after running function on each)
// MongoDB - function getDocumentArray( fnEachDocument, ...documents ) - returns cloned Array of passed documents (after running function on each)
// Purpose: returns cloned Array of passed documents (after running function on each)
// Usage: const docArray = getDocumentArray( fnEachDocument, ...documents ); await coll.insertMany(docArray);
// see the docs for https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany
// esp. "_id Field" https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/#_id-field
// ^ because DURING THE .insert[Many|One]() call, "_id" field is ADDED to the original document! (if missing)
const getDocumentArray = ( fnEachDocument, ...documents ) => (
fnEachDocument ||= ( document => document ),
@DarrenSem
DarrenSem / fizzbuzz expanded - wordmod.js
Last active November 9, 2023 20:38
fizzbuzz expanded - wordmod( limit = 100, words = { 3: "Fizz", 5: "Buzz" }, sep = "\n" )
// FizzBuzz expanded - wordmod.js - because why not
// https://gist.github.com/DarrenSem/3a63b31542487bb1fd38e08976d8d215
let wordmod = ( limit = 100, words = { 3: "Fizz", 5: "Buzz" }, sep = "\n" ) => {
let results = [];
for (let i = 1; i <= limit; i ++) {
let result = "";
for ( let [divisor, word] of Object.entries(words) ) {
@DarrenSem
DarrenSem / range(size, optionalEachFunction, optionalMapFunction).js
Last active February 7, 2024 16:13
range.js (arraySize, optionalMapFunction, optionalEachFunction)
// range(arraySize, optionalMapFunction, optionalEachFunction).js
// https://gist.github.com/DarrenSem/bc0403bcdad09912eb298e6d3b4824fe
const range = ( arraySize, fnMapIndex, fnEachIndexFirst, _indexes ) => (
_indexes = Array.from( Array(arraySize | 0).keys() ), // because [...Array(arraySize | 0).keys()] triggers TypeScript/VSC error: Type 'IterableIterator' is not an array type or a string type.
fnEachIndexFirst && _indexes.forEach( index => fnEachIndexFirst(index) ),
fnMapIndex && ( _indexes = _indexes.map( index => fnMapIndex(index) ) ),
_indexes
);