Skip to content

Instantly share code, notes, and snippets.

View UniBreakfast's full-sized avatar
💡
reinventing basic stuff in order to understand it better

Mykhailo "Ninin" Velykoselskyi UniBreakfast

💡
reinventing basic stuff in order to understand it better
View GitHub Profile
@UniBreakfast
UniBreakfast / getPrototypeTrees.js
Last active September 17, 2023 08:44
Build all available constructors' prototype trees
function getPrototypeTrees() {
const entries = Object.keys(Object.getOwnPropertyDescriptors(window))
.filter(key => key[0] == key[0].toUpperCase() && !key.startsWith('$'))
.map(key => [key, window[key]])
.filter(([_, val]) => typeof val == 'function')
const constructors = Object.fromEntries(entries)
const tree = Object.fromEntries(entries.map(([key, constructor]) =>
[key, Object.assign(Object.create(null), {0: constructor})]))
const trunks = {}
for (const key in constructors) {
@UniBreakfast
UniBreakfast / myConsoleSetUp.js
Last active October 2, 2021 16:44
My console setup
myConsoleSetUp=true
Object.assign(window, {w:window, d:document, b:document.body, l:location, B:Boolean, N:Number, S:String, A:Array, O:Object, F:Function, D:Date, R:RegExp, M:Math, El:Element, tags:{ar:'article', as:'aside', au:'audio', bt:'button', c:'canvas', cp:'caption', d:'div', dg:'dialog', dt:'details', fs:'fieldset', f:'form', fg:'figure', ft:'footer', h:'header', if:'iframe', in:'input', lb:'label', m:'main', ob:'object', op:'option', out:'output', scr:'script', sct:'section', sel:'select', sp:'span', st:'style', sm:'summary', t:'table', tb:'tbody', tf:'tfoot', thd:'thead', tm:'time', tt:'title', tp:'template', ta:'textarea', v:'video'},
cssProps:{bg:'background', c:'color', d:'display', m:'margin', p:'padding', po:'position', t:'top', l:'left', r:'right', b:'bottom', i:'inset', w:'width', h:'height', jc:'justify-content', ji:'justify-items', ai:'align-items', ac:'align-content', bs:'box-sizing', br:'border'},
cssVals:{ab:'absolute', fi:'fixed', f:'flex', b:'block', i:'inline', g:'grid', n:'none',
@UniBreakfast
UniBreakfast / dateGrid4thebrain.js
Created July 9, 2020 09:49
console script to generate a date record structure for importing to thebrain
days = 'вс, пн, вт, ср, чт, пт, сб'.split(', ')
months = 'янв, февр, март, апр, май, июнь, июль, авг, сент, окт, нояб, дек'.split(', ')
[...Array(100).keys()].map(monthShift => {
const date = new Date('2020-07-01')
date.setMonth(date.getMonth()+monthShift)
const year = date.getFullYear()
let month = date.getMonth() + 1
month = month<10? '0'+month : month
const monthLabel = year+'-'+month+', '+months[month-1]
const dates = []
@UniBreakfast
UniBreakfast / setUploader.js
Last active July 6, 2020 13:50
A function to setup uploading inputs, buttons, dropzone, informer etc. It does all the lifting it uploading from a client to a server, you just point it to the elements it should work with and tell it the api endpoint.
function setUploader({pathcbOrStr, namecbOrStr, chooser, starter, dropzone,
informcb, reportcb, fetchArgs}) {
// @pathcbOrStr - path string or function that returns string after getting it somewhere.
// @namecbOrStr - filename string or function that returns string after getting it somewhere.
// @chooser - element to put click handler onto or function that takes handler and assigns it, handler here will show dialog to select file, and if no starter provided it will start uploading at once.
// @starter - element to put click handler onto or function that takes handler and assigns it, handler here will start uploading.
// @dropzone - element to put drag/drop handlers onto, and if no starter provided it will start uploading at once.
// @informcb - function that will take information and use it to show somewhere for example.
// @reportcb - function that will get the resulting promise.
// @fetchArgs - function that will take path, name and body and return an array of arguments for fetch, or the a
@UniBreakfast
UniBreakfast / explore.js
Last active June 19, 2020 04:51
Build a tree object describing the folder structure
const fs = require('fs'), fsp = fs.promises
function date2str(date) {
return JSON.stringify(date).slice(1, 20).replace('T', ' ')
}
function explore(path) {
return fsp.stat(path).then(stats => {
const name = path.match(/[^/\\]*$/)[0],
{mtime, size} = stats, dir = stats.isDirectory(),
@UniBreakfast
UniBreakfast / c4console+p.js
Last active June 15, 2020 08:19
Second version of my c4console util - now it supports promises, especially those you get from fetch(url). I chose the version with methods instead of multiple getters - it looks better because it leaves no unnecesary semi-transparent props in console
// This is kinda bonus feature, and it is used in the main functionality below
console.img =(src, size=0.4, label=' ')=> {
if (src.match(/^data:image\/.*;base64,/))
return Object.assign(new Image(), {src, onload() {
console.log(`%c${label}`,`background: no-repeat url(${src});
padding:0 ${this.width*size}px ${this.height*size}px 4px;
background-size:contain`)
}})
fetch(src).then(r => r.blob()).then(blob => Object.assign(new FileReader(),
{onload() { console.img(this.result, size) }}).readAsDataURL(blob))
@UniBreakfast
UniBreakfast / fetchAsBase64.js
Last active June 14, 2020 10:32
A way to get Base64 string from blob object that you get from fetch
fetch('http://server.com/path/filename.ext')
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(blob) ;
reader.onload = function(){ resolve(this.result) } ;
}) ;
@UniBreakfast
UniBreakfast / console.img(src, size).js
Last active June 14, 2020 20:36
Method for console object to show images in console by providing the URL (or Base64 URI) and optionally size multiplier
// Standalone minimal version (works only with Base64 strings!):
console.img =(src, size=0.4)=> Object.assign(new Image(), {src, onload() {
console.log('%c ', `padding: ${this.height/2*size}px ${this.width/2*size}px;
background: url(${src}) no-repeat; font-size:1px; background-size: contain`)
}})
// Full Standalone version (fetches images if normal link provided instead of Base64 url):
console.img =(src, size=0.4)=> {
if (src.match(/^data:image\/.*;base64,/))
return Object.assign(new Image(), {src, onload() {
@UniBreakfast
UniBreakfast / chain.json.js
Created June 12, 2020 15:42
It does the same as JSON.stringify/parse, but available as methods on values
Object.prototype.json = function(pretty) {
return JSON.stringify(this, ...pretty? [2,2]:[])
}
String.prototype.parse = function() {
return JSON.parse(this)
}
@UniBreakfast
UniBreakfast / stream.pipeIntoFile(path).js
Created June 12, 2020 15:26
Additional method to just write stream (request from standard http server in my case) into the file by providing the path. It creates directories if needed. Returns promise
const Stream = require('stream')
Stream.prototype.pipeIntoFile = function (path) {
path = path.replace(/^\/|\/$/g, '')
const dir = path.replace(/(^|\/)[^\/]*$/, '')
return new Promise(async (resolve, reject)=> {
try {
if (dir) await fsp.mkdir(dir, {recursive: true})
this.on('end', resolve).pipe(fs.createWriteStream(path))
} catch { reject() }