Skip to content

Instantly share code, notes, and snippets.

@booya2nd
Last active September 18, 2024 11:31
Show Gist options
  • Save booya2nd/fc710a24501f0d2b75363b8d76648cc2 to your computer and use it in GitHub Desktop.
Save booya2nd/fc710a24501f0d2b75363b8d76648cc2 to your computer and use it in GitHub Desktop.
Collection of quick try-outs and silly random experiments
const print = x => console.log(JSON.stringify(x, null, 2));
const animals = [
{ value: 'mammals', parent: 'animals' },
{ value: 'animals', parent: null },
{ value: 'poodle', parent: 'dogs' },
{ value: 'dogs', parent: 'mammals' },
{ value: 'labrador',parent: 'dogs' },
{ value: 'siamese', parent: 'cats' },
{ value: 'cats', parent: 'mammals' },
{ value: 'persian', parent: 'cats' }
];
const sortFunction = (sortObj, parent = null, startObj = {}) => {
sortObj
.filter(item => item.parent === parent)
.forEach(item => startObj[item.value] = sortFunction(sortObj, item.value));
return startObj;
};
print(sortFunction([...animals]));
function renderFlatHierarchyDescription(description) {
const index = {};
description.forEach(({ value: child, parent }) => {
index[parent] = index[parent] || {};
index[child] = index[child] || {};
index[parent][child] = index[child];
});
return index['null'] || index;
}
print(renderFlatHierarchyDescription(animals));
let Thenable = (executor, callbacks = [], which = -1, curValue, cb, fulfill, then) => (
fulfill = value => {curValue = value;while(cb=callbacks.shift()) cb[which] && cb[which](value)},
executor(value => fulfill(value, which = 0), value => fulfill(value, which = 1)),
(then = (...thenCbs) => (~which ? thenCbs[which] && thenCbs[which](curValue) : callbacks.push(thenCbs), {then})),
{then}
);
Thenable = (x, callbacks = [], which = -1, curValue, cb, fulfill, then) => (
fulfill = value => {curValue = value;while(cb=callbacks.shift()) cb[which] && cb[which](value)},
x(value => fulfill(value, which = 0), value => fulfill(value, which = 1)),
(then = (...thenCbs) => (~which ? thenCbs[which] && thenCbs[which](curValue) : callbacks.push(thenCbs), {then})),
{then}
);
Thenable((r,j) => j(1337))
.then(
x=>console.log('then:onresolve',x),
e=>console.error('then:onreject',e)
).then(
console.info,console.info
);
0&&(() => {
q = [];
const cmd = (...args) => {
const t = ((x,then) => {
x = [],then = (a,b) => (x.push(a,b),{then});
return { then, catch: a => then(null, a) }
})();
q.push([...args, null, t]);
return t;
};
setTimeout(() => {
const _cmd = q.pop();
const _thenable = _cmd.pop();
console.log(_thenable);
t = _thenable;
}, 1000);
cmd('a').then(
v => console.log('onresolve ',v),
v => console.log('onreject ',v),
);
})();
/*********************************************************/
async function series(tasks) {
let result;
for (let task of tasks) {
result = await task(result);
}
return result;
}
async function series2(tasks) {
const fn = v => typeof v === 'function' ? v : () => v;
return tasks.reduce(
(result, task) => result.then(task, task),
Promise.resolve()
);
}
const SERIES = [
() => Promise.resolve(1),
(v) => new Promise(resolve => resolve(v + 10)),
async (v) => v + 100,
v => v * 6,
];
//series2(SERIES).then(console.log);
// series2(SERIES).then(console.log);
async function promiseSeries3(arr) {
return arr.reduce((acc, fn) => {
return async (...args) => acc(await fn(...args));
})();
}
L = console.log;
promiseSeries3([
async () => 1,
async (v) => v + 10,
async (v) => v + 100
]).then(result => console.log(result));
Promise.all(
[1,2,3,4].map((async n => await n))
).then(L)
function getFramePath(w) {
var x = [];
while(w !== w.top){
x.unshift({iframe: w.frameElement, window: w});
w = w.parent;
}
return x;
}
const googletag = {impl: {pubads: {setAdContentsBySlotForSync: o => Object.values(o).forEach(x => console.log(x._html_))}}};
[...$$(".member_item")]
.map(n => ({
node: n,
name: n.querySelector('.admin_member_real_name').textContent.replace('You • ',''),
link: n.querySelector('.member_image').href,
mail: Object(n.querySelector('.inline_email')).textContent,
img: (n.querySelector('.member_image').style.backgroundImage.match(/(http.*)-\d+/) || [])[1]+'-512'
}))
.forEach(({ node, img }) =>
node.querySelector('.member_image').style.backgroundImage = `url("${img}")`
)
function getAllIframes(win){
let iframes = [];
try {iframes = [...win.document.querySelectorAll('iframe')] }catch(e) {}
return iframes.concat(...iframes.map(({contentWindow}) => getAllIframes(contentWindow)))
}
function getAllWindows(win){
return [win, ...getAllIframes(window).map(i => i.contentWindow).filter(w => { try { return !!w.document } catch(e) { return !1 } })];
}
/* somtag debugging */
// 2384 //is not a valid API command
console.log('::: somtag cmd call', t);
// 2393
((p,c,x) => ((p.t=Date.now(),x=r=>console.log('::: somtag cmd response', t, '\n', { result: r, delta: Date.now()-p.t })),p.then(x).catch(x)))(u,t),0;
// 2956 // t.config.id
console.log('::: somtag load sitescript', n.config.id)
// 2960
console.log('::: somtag load core', t.config.corePath)
function recursive(obj, getChildren, cb){
cb(obj);
[].concat(getChildren(obj)||[]).forEach(o => recursive(o, getChildren, cb))
}
getWindows = win => [...win.document.querySelectorAll('iframe')].map(i => i.contentWindow);
friendlyIframeFilter = win => { try { win = !!win.document } catch(e){ win = !1 } return win };
getFriendlyWindows = win => getWindows(win).filter(friendlyIframeFilter);
getFriendlyWindowsRecursive = win => {
const result = [];
recursive(win, getFriendlyWindows, w => result.push(w));
return result;
};
function getFriendlyWindowsRecursive(win, result) {
// 1. get to the top
var top = (function gettop(){
var result = win;
try { result = win.top } catch(e) {}
})(win)
// 2. traverse down
}
getFriendlyWindowsRecursive(top);
function isfriendly(win){ try { return win.document && true } catch(e) { return false } }
function gettop(win){return (isfriendly(win.top) && win.top) || (isfriendly(win.parent) ? gettop(win.parent) : win)}
function getwins(win){return [].slice.call(win.document.querySelectorAll('iframe')).map(function(i){ return i.contentWindow }).filter(isfriendly)}
function getwinsr(win, r){
var r = r || [win], w = getwins(win);
r.push.apply(r,w);w.forEach(function(w){getwinsr(w,r)});
return r;
}
gettop(window).map(w => w.frameElement);
(function showSomtagInspector() {
var somtags = [];
(function getwindows(rootWindow, result){
[].slice.call(rootWindow.document.getElementsByTagName('iframe')).forEach(function(iframe){
var w = iframe.contentWindow;try { w.document && result.push(w) && getwindows(w, result) } catch(e) { }
});return result;
})(window, [window]).forEach(function(win){win.somtag && somtags.push(win.somtag)});
})();
(function(win,list){return [].concat.apply(list=[].slice.call(win),list.map(arguments.callee))})(top);
((w,r)=>(r=(w,l)=>(l=[].slice.call(w)).concat(...l.map(r)))(w))(top);
// window.open(href, '_blank');
function createRecursely(){
function createSafeObjectsFilter(){
const objectMemory = new Set();
const isObject = object => object && typeof object === 'object';
const isConstructor = object => isObject && typeof object.value === 'function';
return (object) => {
var isObjectInMemory = objectMemory.has(object);
if (!isObjectInMemory) objectMemory.add(object);
return isObject(object) && !isConstructor(object) && !isObjectInMemory;
}
}
function recursive(object, getChildren, iteratorCallback) {
iteratorCallback(object);
[].concat(getChildren(object)||[])
.forEach(object => recursive(object, getChildren, iteratorCallback))
}
function walk(o, cb){
const objectsOnlyFilter = createSafeObjectsFilter();
function getObjectChildren(o){
return Object.values(o).filter(objectsOnlyFilter);
}
recursive(o,getObjectChildren,cb);
}
}
collection = [];
walk({JIRA, jira}, o => collection.push(o));
collection
.filter(o => o && typeof o === 'object' && (!Array.isArray(o) || o.length))
.reduce((acc, o) => {
Object.keys(o).some(k => k.match(/sprint/i) && (acc[k] = o[k]));
return acc;
}, {})
new Promise(function(r,x,xhr){
xhr = new XMLHttpRequest();xhr.open("GET", `https://jira.sim-technik.de/rest/greenhopper/1.0/sprint/picker`);
xhr.addEventListener("load", r);xhr.addEventListener("error", x);xhr.send();
})
.then(event => JSON.parse(event.target.responseText).suggestions)
.then(sugg => sugg.filter(function(s){s.stateKey === "ACTIVE"}))
.then(v => v.suggestions.sort((a,b)=>new Date(b.date||0)-new Date(a.date||0))[0])
.then(o => Object(o).id)
.catch(e => -1)
.then(sprintId => `/secure/CreateIssueDetails!init.jspa?pid=20023&issuetype=17&summary=TODO+SUMMARY&description=TODO+DESCRIPTION&labels=adtech_platform&labels=adtech_development&assignee=dev.adtech&priority=3&customfield_10460=${sprintId}&reporter=${JIRA&&JIRA.Users.LoggedInUser.userName()||''}`)
.then(url => window.open(url, '_blank'));
function sort(a, c) {
return a.sort(function(a, b){
var v = 0; c.some(function(s){v = s(a, b);return v !== 0;});return v;
});
}
(function(){
function sort(a,c){return a.sort(function(a,b){var v=0;c.some(function(s){v=s(a, b);return v!==0;});return v;});}
var xhr = new XMLHttpRequest();xhr.open("GET", `https://jira.sim-technik.de/rest/greenhopper/1.0/sprint/picker`);
xhr.addEventListener("load", onxhr.bind(null, null));xhr.addEventListener("error", onxhr.bind(null, null));xhr.send();
function getsprintid(res){
var sprintId = -1;
try {
sort(
(JSON.parse(res.target.responseText).suggestions || []),
function(a,b){return a.stateKey === "ACTIVE"});
} catch(e) {}
return sprintId;
}
function onxhr(err, res){
getsprintid(res)
}
})();
javascript:(function (d, w) {
var debug = function (object, objectString, methodName, debugFunction) {
var a = arguments, x = object[methodName], novalue = {};
object[methodName] = function () {
var debugFunctionReturnValue = debugFunction ? debugFunction(novalue, a, arguments) : "";
debugFunctionReturnValue !== novalue && console.trace(objectString + "." + methodName + "()", arguments, debugFunctionReturnValue);
return x.apply(this, arguments);
};
};
debug(WebSocket.prototype, "WebSocket", "send");
debug(document, "document", "write");
debug(document, "document", "writeln");
debug(XMLHttpRequest.prototype, "XMLHttpRequest", "open");
debug(Node.prototype, "*", "appendChild", function (novalue, aspectArgs, callArgs) {
var node = callArgs[0];
return /SCRIPT|OBJECT|EMBED|LINK|STYLE/.test(node.tagName) ? (node.src || node.data || setTimeout(function () {
console.log(node.src || node.href || node.data);
}), node) : novalue;
});
})();
function spyOn(context, method) {
const original = context[method];
const calls = [];
const returns = [];
context[method] = function (...args) {
calls.push(args);
const value = original.apply(this, args);
returns.push(value);
return value;
};
const spyObj = {
name: `${{}.toString.call(context)}::${original.name}`,
original,
calls,
returns,
remove: () => {
calls.length = returns.length = 0;
context[method] = original;
const found = spyOn.spies.indexOf(spyObj);
if (found !== -1) spyOn.spies.splice(found, 1);
}
};
spyOn.spies.push(spyObj);
return spyObj;
}
spyOn.spies = [];
global.spyOn = spyOn;
// spyOn(global.XMLHttpRequest.prototype, 'open');
// spyOn(global, 'fetch');
function callSomtag(fn){
var path=n=>[...Array(2)].reduce((r,x,p)=>([p]=r,(p=p&&p.parentElement)&&r.unshift(p),r),[n]);
var node2str=n=>n&&n.nodeName+(n.id?'#'+n.id:'')+(n.className?'.'+n.className:'')||'top';
var results = [top, ...((w,r)=>(r=(w,l)=>(l=[].slice.call(w)).concat(...l.map(r)))(w))(top)]
.filter(w=>{try{return w.somtag&&w.somtag.cmd}catch{return !1}})
.map(w => ({result:fn(w.somtag),window:w,somtag:w.somtag,path:path(w.frameElement).map(node2str).join(' > ')}));
return Promise.all(results);
}
callSomtag(somtag => somtag.cmd('getAdTrace'));
[top, ...((w,r)=>(r=(w,l)=>(l=[].slice.call(w)).concat(...l.map(r)))(w))(top)].filter(w=>{try{return !!w.document}catch{}});
[].concat.apply([top],((w,r)=>(r=(w,l)=>[].concat.apply((l=[].slice.call(w)),l.map(r)))(w))(top));
function intersects(a,b){ return (a=a.getBoundingClientRect(),b=b.getBoundingClientRect())&&!(a.right<b.left || a.left>b.right || a.bottom < b.top || a.top > b.bottom) };
intersects(
document.querySelector(temp1.data.options.container),
document.querySelector('.rectangle-home')
);
somtag.cmd('insertAd', 'rectangle1', {container: '#somtag-container-rectangle'}, function (error, ad) {
if (ad) {
var adConfig = ad.data.adConfig, option = ad.data.option, classList = document.body.classList;
adConfig.productName && classList.add('has-' + adConfig.productName);
var iframe = document.querySelector(option.container + ' iframe.somtag');
Object(iframe).offsetHeight > 400 && classList.add('has-' + adConfig.slotName + '-overlap');
}
});
l = somtag.core.getLog();
function createSafeClone(){
const seen = [];
function getChildren(obj){
const children = Array.isArray(obj) && obj || typeof obj === 'object' && Object.entries(obj);
return children;
}
return function safeClone(obj, result={}){
const children = Array.isArray(obj) && obj || typeof obj === 'object' && Object.entries(obj);
children.forEach(([key, value])=>{
const isObject = typeof value === 'object';
const isSeenObject = seen.includes(value);
isObject && !isSeenObject && seen.push(v);
const v = !isObject
? value
: isSeenObject
? '#recursive'
: safeClone(value, result);
result[key] = v;
});
return result;
}
};
var clone = createSafeClone();
debugger;
clone(l);
var isObject = o => typeof o === 'object';
function* recursive(object, getChildren){
console.log('...');
yield 0;
//getChildren(object)
// (() => {yield 1;})();
};
var iterable = recursive([1,[2,[3]]]);
for (var a of iterable) {}
// https://www.geeksforgeeks.org/coin-change-dp-7/
function coinChangeCount(coins, value){
const counts = [...Array(value+1)].fill(0);
counts[0] = 1;
coins.forEach((coin) => {
// steps value - coin
for (let i=coin; i<=value; i++) {
const v = i;
counts[v] += counts[v - coin];
console.log({i, v,cache:counts+''});
}
});
return counts[value];
}
count([1,2], 2);
var cache = new Map();
function get(obj, key){
try { return Object(obj)[key] } catch(e) { return e }
};
function cloneDeep(obj = {}, path=[]) {
if (typeof obj !== 'object' || obj === null) return obj;
if (Array.isArray(obj)) {
const newArr = [];
obj.forEach((item, index) => {
newArr[index] = cloneDeep(item);
});
return newArr;
}
const newObj = {};
Object.keys(obj).forEach((key) => {
const property = get(obj, key);
const type = typeof property;
switch (type) {
case 'object':
if (Array.isArray(property)) {
newObj[key] = [];
property.forEach((val) => {
newObj[key].push(cloneDeep(val));
});
} else {
if (!cache.has(property)) {
cache.set(property, `#${cache.size}`);
newObj[key] = cloneDeep(property);
} else {
newObj[key] = cache.get(property);
}
}
break;
default:
newObj[key] = property;
break;
}
});
return newObj;
}
cloneDeep(window);
function sum(items) {
return sum.reduce((a,b) => a+b);
}
function cut(items, amount) {
const sort = [...items].sort((a,b) => a-b);
const cutNum = String(amount).includes('%') ? items.length * parseFloat(amount)/100 : amount;
const cutSide = cutNum/2 | 0;
return items.slice(cutSide, items.length-cutSide)
}
function avg(items, cutoff=0) {
const cutted = cut(items, cutoff);
return sum(cutted) / cutted.length;
}
cut([1,2,3,4,5,6,7,8,9,10], 0)
// print transportconfig input/output if reco exists:
Object.fromEntries(
somtag.core.getLog(0, 'transport')
.map(([,io])=>
[[io.input.blockName||'', io.input.slotName||'', io.input.productName||'']+'', io]
)
.filter(([k,{result}]) => result.bidding.yieldProbe.recommendations)
);
function sortObject(obj, predicate){
return Object.fromEntries(
Object.entries(obj).sort(predicate)
)
}
(() => {
const sums = [0,0,0];
const criteria = Object.entries({
hasCssVar: ([browser]) => browser.match(
/Chrome|Edge|(Firefox (3[1-9]|[4-9][0-9])|Opera (3[6-9]|[4-9][0-9])|Yandex|Safari (9|[1-9][0-9]))/i
)
});
const all = data.split('\n').map(l => l.split('\t').map((v,i) => isNaN(v*1)?v:(sums[i]+=v*1,v*1)));
const relev = all.filter(row => criteria.every(criterion => criterion(row)));
console.log(relev);
})();
(function MOCK__SCOPE__INJECTIONS(){
database = (cred) => ({name: 'database', cred });
env = { CREDENTIALS: '{"user":"nameA","pass":"secret"}'};
})();
MODULE__Database = (() => {
/* import */ database /* from 'database' */;
/* import */ env /* from 'env' */;
function parseCredentials(){ return JSON.parse(env.CREDENTIALS)}
class Database {
static #instance;
static getInstance() { return Database.instance || (Database.instance = database(parseCredentials())); }
}
return Database;
})();
MODULE__Database_POJO = (() => {
/* import */ database /* from 'database' */;
/* import */ env /* from 'env' */;
function parseCredentials(){ return JSON.parse(env.CREDENTIALS)}
let instance = null;
return { getInstance: () => instance || (instance = database(parseCredentials())) }
})();
MODULE__Database_Multiton = (() => {
/* import */ database /* from 'database' */;
/* import */ env /* from 'env' */;
function parseCredentials(){ return JSON.parse(env.CREDENTIALS)}
const instances = new Map();
return {
getInstance(identifier) {
instances.has(identifier) || instances.set(identifier, database(parseCredentials()));
return instances.get(identifier);
}
}
})();
/* import */ Database /* from 'Database'*/ = MODULE__Database;
/* import */ Database2 /* from 'Database'*/ = MODULE__Database_POJO;
/* import */ Database3 /* from 'Database'*/ = MODULE__Database_Multiton;
//envLoader();
db = Database.getInstance();
console.assert(db === Database.getInstance(), 'Class.getInstance should be same reference');
db2 = Database2.getInstance();
console.assert(db2 === Database2.getInstance(), 'Object.getInstance should be same reference');
db3 = Database3.getInstance();
console.assert(db3 === Database3.getInstance(), 'multiton Object.getInstance should be same reference');
db4 = Database3.getInstance(env);
console.assert(db4 === Database3.getInstance(env), 'multiton Object.getInstance should be same reference');
console.assert(db3 !== db4, 'multiton Object.getInstance must not be same reference');
p1 = [['10:30','11:00'],['11:00','11:45'],['12:15','13:15'],['15:00','16:15']];
p2 = [['8:30','9:45'],['10:15','10:45'],['10:45','11:00'],['11:30','12:00'],['12:00','13:00'],['14:30','17:00']];
constraints = [['0:00','8:00'],['12:00','12:30'],['18:00','24:00']];
function toNum(timeString){
const [hours, minutes] = timeString.split(':');
return hours*60 + minutes*1;
}
function formatTime(minutes){
const hours = minutes/60|0 || 0;
const mins = (minutes%60+'').padStart(2,'0');
return `${hours}:${mins}`;
}
function calendarToNum(personCalendar){
return personCalendar.map(timeRange => timeRange.map(toNum))
}
function merge(...calendars){
const mergedCals = [].concat(...calendars);
mergedCals.sort(([startTimeA],[startTimeB]) => startTimeA - startTimeB);
let result = [mergedCals.shift()];
for (let i=1,l=mergedCals.length; i<l; i++){
const {[result.length-1]: latest} = result;
const next = mergedCals[i];
const [[start1, end1],[start2, end2]] = [latest, next];
const hasIntersection = end1 >= start2;
if (hasIntersection) {
latest[1] = Math.max(end1, end2);
i++; // skip next
} else result.push(next);
}
return result;
}
function gaps(timeRanges, minLength=0){
return timeRanges.reduce((acc, curr, i, arr) => {
const next = arr[i+1] || [];
const [[,end1],[start2]] = [curr, next];
if (start2 - end1 >= minLength) acc.push([end1, start2]);
return acc;
}, []);
}
numericCals = [p1,p2,constraints].map(calendarToNum);
gaps(merge(...numericCals)).map(entries => entries.map(formatTime));
// merge(...numericCals).map(entries => entries.map(formatTime));
export function deepFreeze(object, maxDepth = 10) {
if (maxDepth > 0) {
Object.values(object).forEach((value) => {
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
deepFreeze(value, maxDepth - 1);
}
});
}
return Object.freeze(object);
}
(function(s,o,m){
(m=s.body.appendChild(s.createElement('script'))).src=o;
m.onload=function(){window.executeCoreTests()}
})(document,'https://adserver.71i.de/somtag/core/prerelease/v2/regression-test.js');
(function idleMinesConvert(){
function numToString(number, charList = []) {
const chrs = typeof charList === 'string' ? charList.split('') : charList;
const base = chrs.length, exp = getExp(base, number);
let exponentIterator = exp + 1, temp = number, result = '';
while(exponentIterator--) {
result += chrs[temp / Math.pow(base, exponentIterator) | 0];
temp %= Math.pow(base, exponentIterator);
}
return result;
}
function toBaseCharsOnly(number) {
const chrs = 'abcdefghijklmnopqrstuvwxyz';
return numToString(number, chrs).padStart(2,'a');
}
function getSuffix(thousandExp){
const staticChrs = ['', 'K', 'M', 'B', 'T'];
return staticChrs[thousandExp] ?? toBaseCharsOnly(thousandExp - staticChrs.length);
}
function getSuffixCheap(thousandExp){
const staticChrs = ',K,M,B,T,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az,ba,bb,bc,bd,be,bf,bg,bh,bi,bj,bk,bl,bm,bn,bo,bp,bq,br,bs,bt,bu,bv,bw,bx,by,bz'.split(',');
return staticChrs[thousandExp];
}
function getExp(base, value) {
return Math.log(value) / Math.log(base) | 0;
}
function toIdleMineNumber(number) {
const exp = getExp(1000, number);
const maxThousands = Math.pow(1000, exp);
const numValue = Math.round(number / maxThousands * 100) / 100;
const result = numValue + getSuffixCheap(exp);
console.log(result, BigInt(number).toString());
return result;
}
return [
toIdleMineNumber(123) === '123',
toIdleMineNumber(1_000) === '1K',
toIdleMineNumber(1_500) === '1.5K',
toIdleMineNumber(1_580) === '1.58K',
toIdleMineNumber(1_000_000) === '1M',
toIdleMineNumber(1_000_000_000) === '1B',
toIdleMineNumber(1_000_000_000_000) === '1T',
toIdleMineNumber(1_000_000_000_000_000) === '1aa',
toIdleMineNumber(1_000_000_000_000_000_000_000_000) === '1ad',
toIdleMineNumber(1e27) === '1ae',
toIdleMineNumber(1e30) === '1af',
toIdleMineNumber(1e33) === '1ag',
toIdleMineNumber(1e36) === '1ah',
toIdleMineNumber(1e39) === '1ai',
toIdleMineNumber(1e42) === '1aj',
toIdleMineNumber(1e93) === '1ba',
toIdleMineNumber(1e96) === '1bb'
];
})()
// https://github.com/SevenOneMedia/adtec-core/pull/1336/files
isNuggKeyValueRegex = /\w\d{1,2}=\d/;
isNuggKeyValue = entry => isNuggKeyValueRegex.test(entry);
yieldRequestNuggadKeyValues = yiedRequestDecoded.split('&').filter(isNuggKeyValue);
missingYlNuggadKeyValuesFromCookie = yieldRequestNuggadKeyValues.filter(ylKv => decodedCookieData.includes(ylKv));
errors = missingYlNuggadKeyValuesFromCookie.map(kv => `yieldProbe call contains targeting key-val ${kv} that is not present in the nuggad cookie`);
function createQ({ chunksize = 1}) {
const queue = [];
let running = 0;
function next(){
const chunks = queue.splice(0, chunksize - running);
running += chunks.map(run).length;
}
async function run(task){
try { await task() } catch { }
running > 0 && --running; next();
}
function add(...tasks){
queue.push(...tasks);
next();
}
return {
add
}
}
class asyncQ {
#queue = [];
#running = 0;
#chunksize = 1;
constructor(chunksize) {
this.chunksize ||= chunksize;
}
#next() {
const chunks = this.queue.splice(0, this.chunksize - this.running);
this.running += chunks.map(this.run).length;
}
async #run(task){
try { await task() } catch { }
this.running > 0 && --this.running; this.next();
}
add(...tasks){
this.queue.push(...tasks);
this.next();
}
}
q = createQ({ chunksize: 6 });
to = (t,v) => new Promise(r => setTimeout(()=>r(v), t));
entries = [...Array(20)].map((x,i) => () => (console.log(i),to(i*1000,i)));
q.add(...entries);
n = (n,l=2) => (n+'').padStart(l,'0');
h = d => (a=['Hours','Minutes','Seconds'].map(g=>n(d['get'+g]())),a.join(':')+'.'+n(d.getMilliseconds(),3))
[somtag.core.getLog(0,'insert')]
.forEach((log,i) => {
console.group('somtag.core.getLog #'+i);
const tInits=somtag.core.getLog(0,'core.init').map(([,,t])=>t);
log.forEach(([msg, data, time]) => {
const t0 = tInits.find((t,i,ts) => ts[i+1] ? time-ts[i+1] < 0 : !0);
console.log( new Date(time).toISOString().match(/\d+:\d+:\d+.\d+/)[0], { 't₀Δ': time - t0, msg, data })
});
console.groupEnd();
});
window.results ||= {}, mark = performance.getEntriesByName('insertAd')[0], inits = somtag.core.getLog(0,'eraseDisplaySlots');
somtag.core.getLog(0,/\[rendered\]/i).map(([msg, data, time]) => {
const entries = (results[msg] ||= []), index = entries.length;
const initTo = inits?.[index]?.[2] ?? inits?.[index-1]?.[2], markTo = mark.startTime + performance.timeOrigin;
entries.push({ mark: time - markTo, init: time - initTo });
});
results;
function findAnnotated(selector, doc=document) {
const shadowElements = [...selector.matchAll(/(?:(.*?)§([\w-_]+|\[.*?\]))|(.+)/ig)];
return shadowElements.reduce((el, [,pre='', shadow='', post='']) =>
post ? el?.querySelector(post) : el?.querySelector(`${pre} ${shadow}`)?.shadowRoot
, doc)
};
findAnnotated('body §cmp-banner §[nested] §[variant*="prim"] button>slot');
// ES6
function findLazy(selector, scope=document) {
return selector.trim().split(/(?<!>) +(?!>)/).reduce((el, part) =>
(el?.shadowRoot || el?.documentElement || el)?.querySelector(part), scope
)
};
findLazy('body cmp-banner [nested] [variant*="prim"] button>slot');
// ES5
function findLazy(selector, scope) {
scope = scope || document;
return selector.trim().split(/(?<!>) +(?!>)/).reduce(function(el, part) {
el = Object(el);
var qs = (el.shadowRoot || el.documentElement || el).querySelector;
return qs && qs(part);
}, scope)
};
findLazy('body cmp-banner [nested] [variant*="prim"] button>slot');
async function createTravisApiRequest(apiParams) {
const params = new URLSearchParams(apiParams);
return (await fetch(`https://api.travis-ci.com/repo/SevenOneMedia%2Fadtec-core/builds?${params}`, {
method: 'GET',
headers: {
'Travis-API-Version': 3,
'Authorization': 'token FrezZQHznDbVGAdhWXqeVg',
'Content-Type': 'application/json'
},
})).json();
}
async function* loadTravisApi(maxResults=Infinity) {
const limit = Math.min(maxResults, 100);
let offset = 0;
while(isFinite(offset)) {
const response = await createTravisApiRequest({ limit, offset });
offset = response?.['@pagination']?.next?.offset;
yield response;
}
};
if (!results) {
results = [];
for await (let x of loadTravisApi()) { results.push(x); }
results;
}
/*** arrayGroup arraySplit ***/
function arrayGroup(array, cb) {
return array.reduce((acc, ...args) => {
const [entry] = args;
const groupNames = [].concat(cb(...args));
groupNames.forEach(groupName => (acc[groupName] ||= []).push(entry));
return acc;
}, {});
}
const ARRAY_SPLIT_BEFORE = 'before';
const ARRAY_SPLIT_AFTER = 'after';
function arraySplit(array, predicate, splitWhen = ARRAY_SPLIT_BEFORE){
return array.reduce((acc, ...args) => {
const [entry] = args;
const isSplitPoint = predicate(...args);
if (isSplitPoint && splitWhen === ARRAY_SPLIT_BEFORE) acc.push([]);
acc.at(-1).push(entry);
if (isSplitPoint && splitWhen === ARRAY_SPLIT_AFTER) acc.push([]);
return acc;
}, [[]]);
}
/*************** slice somtag log ***********************/
function Entry(payload) {
return { payload, next: null, previous: null, root: null }
}
function EntryList(name) {
let recent = null;
return {
name,
entries: [],
add(entry) {
this.entries.push(entry);
entry.root = this.entries[0];
recent && (recent.next = entry);
entry.previous = recent;
recent = entry;
}
}
};
function isInit(msg) {
return msg === 'eraseDisplaySlots: reset all display slots';
};
var LOGS = {
get entries() { return this.inits.flatMap(list => list.entries)},
byMessage: {},
inits: [],
filterEntries(criteria, list = this.inits) {
const arrList = [].concat(list);
const arrCriteria = [].concat(criteria);
return arrList.map(
list => list.entries.filter(
entry => arrCriteria.every(
criterion => criterion(entry, list)
)
)
).filter(({ length }) => length > 0)
}
};
somtag.core.getLog(0).forEach(([msg, data, time], logs) => {
const { inits, byMessage } = LOGS;
const createNewList = inits.length === 0 || isInit(msg);
if (createNewList) inits.push(new EntryList(inits.length + 1));
const entry = new Entry({msg, data, time});
(byMessage[msg] ||= []).push(entry);
const currentLifecycle = inits[inits.length-1];
currentLifecycle.add(entry);
});
LOGS.filterEntries(({ payload }) => payload.msg.match(/consent/))
function getInitLifeCycles(){
const logs = somtag.core.getLog(0);
const [,...initLifeCycles] = arraySplit(logs, ([msg]) => msg.startsWith('eraseDisplaySlots'));
return initLifeCycles;
}
function exploreSlotName([msg, data]){
return Object(data)?.slot || Object(data)?.slotName || msg.match(/[a-z]{5,}\d/)?.[0]
}
arrayGroup(somtag.core.getLog(0), exploreSlotName);
/*** jira-daily extension ***/
users=['SOM DEV','Andres','Doga','Emrah','Ivan','Marcel','Tobias B','Ubira','martin'];
function myhook({state}){try{
const n =state.pane.node;
Object.entries(state.users)
.filter(([name])=>users.find(user=>name.match(user)))
.forEach(([,entry])=>n.insertBefore(n.firstChild, entry.node));
}catch(e){console.log(e)}};
__JIRA_USERPICKER.on(__JIRA_USERPICKER.hooks.LOOP, (...args) => myhook(...args));
/*** Deferreds ***/
const NOOP = x => x;
class Deferred extends Promise {
constructor(executorFn) {
let localResolve;
let localReject;
super((resolve, reject) => {
localResolve = resolve;
localReject = reject;
executorFn(localResolve, localReject);
});
this.resolve = localResolve;
this.reject = localReject;
}
}
export function deferred(executorFn = NOOP) {
let resolveDeferred;
let rejectDeferred;
const internalPromise = new Promise((resolvePromise, rejectPromise) => {
resolveDeferred = resolvePromise;
rejectDeferred = rejectPromise;
executorFn(resolveDeferred, rejectDeferred);
});
internalPromise.resolve = resolveDeferred;
internalPromise.reject = rejectDeferred;
return internalPromise;
}
export function deferred1() {
let resolveDeferred;
let rejectDeferred;
const internalPromise = new Promise((resolvePromise, rejectPromise) => {
resolveDeferred = resolvePromise;
rejectDeferred = rejectPromise;
});
return {
promise: internalPromise,
resolve: resolveDeferred,
reject: rejectDeferred
};
}
/*** Remove porperty from object/array ***/
function removeArr1(arr, indexes) {
indexes.forEach((index, n) => arr.splice(index-n,1))
return arr;
}
function removeSingleProp(obj, path) {
const properties = path.replace(/\[(.+?)\]/,'.$1').split('.');
const last = properties.pop();
// eslint-disable-next-line no-return-assign
const ref = properties.reduce((next, prop) => next?.[prop], obj);
Array.isArray(ref) ? (ref.splice(last,1)) : (delete ref[last]);
return obj;
}
export function get(obj, path, defaultValue) {
const properties = path.split('.');
return properties.reduce((next, prop) => next?.[prop] ?? defaultValue, obj);
}
export function set(obj, path, value) {
const properties = path.split('.');
const last = properties.pop();
// eslint-disable-next-line no-return-assign
const ref = properties.reduce((next, prop) => (Object(next)[prop] ||= {}), obj);
ref[last] = value;
}
export function remove(obj, path) {
const properties = path.split('.');
const last = properties.pop();
// eslint-disable-next-line no-return-assign
const ref = properties.reduce((next, prop) => next?.[prop], obj);
delete ref[last];
}
export function has(obj, path) {
const NOT_FOUND = Symbol('property-not-found');
const properties = path.split('.');
return properties.reduce(
(next, prop) => (prop in Object(next) ? next[prop] : NOT_FOUND),
obj
) !== NOT_FOUND;
}
/*** TTR ***/
MAX_TTR_DIFF=150;
MAX_TTR_WIN = 16;
function prob(a, b, clamp) {
return 1/(1+10**((b-a)/clamp));
}
function TTR(a, b, { win } = {}) {
const p = prob(a, b, MAX_TTR_DIFF);
return (win - p) * MAX_TTR_WIN;
}
function TTR2(a, b, { sets } = {}) {
const s = sets**(sets > 1 ? -1 : 1)
const p = prob(a, b, MAX_TTR_DIFF);
const r = ((sets>1) - p) * MAX_TTR_WIN;
return r * (1-s)|0;
}
[
TTR(1000,1000, { win: true }), // 8
TTR(1000,1000, { win: false }), // -8
TTR2(1000,1000, { sets: 3/2 }), // 2
TTR2(1000,1000, { sets: 3/1 }), // 5
TTR2(1000,1000, { sets: 3/0 }), // 8
TTR2(1000,1000, { sets: 2/3 }), // -2
TTR2(1000,1000, { sets: 1/3 }), // -5
TTR2(1000,1000, { sets: 0/3 }) // -8
]
window._kill && window._kill();
function handle(w, constructed) {
['open', 'message', 'error', 'close'].forEach(n => {
w.addEventListener(n, e => {
console.log(`::: Websocket ${w.id} <${n}>:::`, e?.data);
})
});
}
function _kill(){
console.clear();
clearInterval(window.__I);
clearInterval(window.__K);
WebSocket = window._W ?? WebSocket;
};
(function _watch(kill) {
window._W = WebSocket;
WebSocket = function(...args){
const w = new _W(...args);
w.id = Date.now().toString(36).split('').reverse().join('');
handle(w, ...args);
return w;
}
__I = setInterval(() => {
document.querySelector('a.sync-btn')?.click();
setTimeout(() => { document.querySelector('.refresh-box a.btn')?.click() }, 5e3)
}, 15e3);
})(_kill);
input = `Spitzbergen Novosibirsk 3520
Spitzbergen Prag 3180
Spitzbergen Denver 6350
Denver Prag 8420
Denver LaPaz 7330
Denver Kinshasa 12890
LaPaz Kinshase 9180
LaPaz Prag 10900
Kinshasa Prag 6060
Kinshasa Novosibirsk 9020
Prag Novosibirsk 4480`;
nodes = input.split('\n').reduce((acc, str) => {
const [a,b,dist] = str.split(' ');
acc[a]||={};
acc[a][b] = dist*1;
return acc;
}, {});
function paths(node){
nodes
}
function getDist(nodes){return nodes.reduce((acc, n) => acc+n, 0)};
paths(nodes['Spitzbergen']).map(getDist);
setTimeout(() => console.log('A'), 0);
Promise.resolve(
console.log('B')
).then(() =>
console.log('C')
);
(async () => {
console.log('D');
await console.log('E');
await Promise.resolve(
console.log('F')
);
console.log('G')
})();
console.log('H');
const getParents = (startNode) => {
let node = startNode, result = [];
while(node = Object(node).parentElement) { result.push(node); }
return result;
}
const findParent = (startNode, selector) =>
getParents(startNode).find(parent => parent.matches(selector));
// iframe observer
(() => {
const x = global.HTMLIFrameElement.prototype.setAttribute;
global.HTMLIFrameElement.prototype.setAttribute = function (...args) {
console.log(':: iframe setAttribute', ...args, this.id || this.name || this.src || this.srcdoc);
return x.call(this, ...args);
};
})();
(() => {
const mut = new global.MutationObserver((list) => {
const changes = Object.fromEntries(
list.map(record => [record.attributeName, { iframe: record.target, ...record }])
);
console.log(':: iframe mutations', changes);
});
const x = global.document.createElement;
global.document.createElement = function (type) {
const element = x.call(this, type);
if (type.toLowerCase() === 'iframe') {
Object.defineProperty(element, 'sandbox', { value: '' });
Object.defineProperty(element, 'csp', { value: '' });
mut.observe(element, { attributes: true });
}
return element;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment