Skip to content

Instantly share code, notes, and snippets.

@mLuby
mLuby / promisersSequenced.ts
Last active May 18, 2023 20:20
Run Promisers (()=>Promise) in sequence rather than in parallel
type Promiser = () => Promise<any>;
function promisersSequenced([nextPromiser, ...otherPromisers]: Promiser[]) : Promise<any> {
return nextPromiser().then(() => otherPromisers.length && promisersSequenced(otherPromisers));
};
const responsePs: Promise<any>[] = [...new Array(3)].map((_, i) => new Promise(resolve => setTimeout(() => resolve(console.log("P idx:" + i)), 100 - i * 10)));
const responsePfs: Promiser[] = [...new Array(3)].map((_, i) => () => new Promise(resolve => setTimeout(() => resolve(console.log("Pf idx:" + i)), 100 - i * 10)));
(async function mainPs () {
console.log("Started");
@mLuby
mLuby / unnecessary_lodash.js
Last active February 7, 2023 18:44
To underscore the point that you don't need Lodash…
////////
// _.get
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c'); // => 3
object?.a?.[0]?.b?.c; // => 3
_.get(object, 'a.b.c', 'default'); // => 'default'
object?.a?.b?.c ?? 'default'; // => 'default'
@mLuby
mLuby / nodejs_1-liner_server.md
Last active April 27, 2023 21:52
NodeJS Server 1-liners

Submitted for your approval, a NodeJS solution in 123 chars. ⛳

r=require;r("http").createServer((i,o)=>r("stream").pipeline(r("fs").createReadStream(i.url.slice(1)),o,_=>_)).listen(8080)

Run it in bash to serve files relative to that directory, and also any file on your computer if given an absolute path. 😱

node -e 'r=require;r("http").createServer((i,o)=>r("stream").pipeline(r("fs").createReadStream(i.url.slice(1)),o,e=>console.log(i.url,e))).listen(8080)'
@mLuby
mLuby / ZombieBridge.js
Last active November 24, 2022 03:56
Help travellers get from one side of a bridge to another with only a lantern to guide them. (Solution is random/brute force, not exhaustive/optimal.)
// Set up initial constraints.
GOAL_TOTAL_TIME = parseInt(process.argv.slice(2)[1]); // if optimal time unknown, set 0.
MAX_ATTEMPTS = parseInt(process.argv.slice(2)[2]); // I don't recommend going past 50000.
try { INITIAL_AT_RISK_PEOPLE = JSON.parse(process.argv.slice(2)[0]); } finally {
if (typeof INITIAL_AT_RISK_PEOPLE === 'undefined' || isNaN(GOAL_TOTAL_TIME) || isNaN(MAX_ATTEMPTS) || !Array.isArray(INITIAL_AT_RISK_PEOPLE)) {
console.log("\nInvalid command format. The command should look like this (space-sensitive):\n");
console.log(" node ZombieBridge.js [1,2,5,10] 17 1000\n");
return; // Return early since the command won't work.
} else console.log("INITIAL CONSTRAINTS:", {INITIAL_AT_RISK_PEOPLE,GOAL_TOTAL_TIME, MAX_ATTEMPTS}, "\n");
}
@mLuby
mLuby / example-ftp.js
Created August 27, 2022 03:09
Example FTP script that connects to an FTP server, lists the directory's files, chooses one to download, renames it locally, then re-uploads it.
import fs from "fs";
import { fileURLToPath } from "url";
import {join, parse, dirname} from "path";
import FtpClient from "ftp";
const FTP_READY_EVENT = "ready";
const FS_CLOSE_EVENT = "close";
const config = { // See https://www.npmjs.com/package/ftp#methods.
host: "ftp.dlptest.com",
@mLuby
mLuby / all-but-first-and-last-via-tail.sh
Created February 4, 2020 16:52
Exclude first and last lines of example.txt just using tail and pipe in bash.
tail -n +2 example.txt | tail -r | tail -n +2 | tail -r
# -n +2 means all but 1 line at the end (+1 does include last line)
# -r means reverse
@mLuby
mLuby / tetris.html
Last active August 14, 2020 16:17
Tetris with Emojis, works in browser or from NodeJS
// <!DOCTYPE html><html><head><meta charset="utf-8"></head><body></body><script>
class Piece {
constructor([startRow, startCol], shape) {
const colors = {I: "🎽", O: "🌕", T: "⚛️ ", S: "❇️ ", Z: "🅰️ ", J: "🛂", L: "✴️ "};
const shapes = {
I: [[1,1,1,1]],
O: [[1,1], [1,1]],
T: [[0,1,0], [1,1,1]],
S: [[0,1,1], [1,1,0]],
@mLuby
mLuby / sortOrderBy.js
Created December 13, 2018 21:28
list.sort(orderBy(["first", "second", "…", "penultimate", "last"])
// Allows user to list some (but not all) items to be sorted in the specified order.
// If the ellipsis character … (option-; on Mac) is present, can specify order of things to go after everything else.
const debug = false ? console.log : ()=>{}
console.log(["!","o","r","s","d","e","t"].sort(orderBy(["s","o","…","e","d","!"]))) // s o r t e d !
console.log(["b","c","a"].sort(orderBy(["c"]))) // c b a
function orderBy (ordering) { return (a, b) => { // columns specified in orderOfColumns come first, then other columns
const rest_index = ordering.indexOf("…") === -1 ? Infinity : ordering.indexOf("…")
@mLuby
mLuby / ParseQueryString.js
Created November 21, 2018 18:45
One-liner for parsing URL query strings
location.search.substring(1).split("&").reduce((queryObj, kv) => Object.assign(queryObj, {[decodeURIComponent(kv.split("=")[0])]: decodeURIComponent(kv.split("=")[1])}), {})