Last active
August 9, 2020 17:28
-
-
Save bo33b/14270fbeefc4fd79ff52 to your computer and use it in GitHub Desktop.
Awesome JavaScript tricks and code snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import("https://hongru.github.io/proj/canvas2image/canvas2image.js").then(function(module) { | |
alert("module ready"); | |
let width=1500;height=950; | |
Canvas2Image.saveAsJPEG(canvasObj, width, height) | |
}); | |
javascript:!function(){document.head.appendChild(document.createElement('script')).src="//rawgithub.com/bo33b.js"}(); | |
javascript:(function(d){d.head.appendChild(d.createElement('script')).src="//rawgithub.com/bo33b.js"})(document); | |
javascript:var iables,ip="192.168.1.152:8080",q=location.search.substr(1).split("&").reduce((o,i,d,k,v)=>(d=decodeURIComponent,[k,v]=i.split("="),o[d(k)]=v&&d(v),o),{}),y=location.host.includes('youtube'),v=y&&`plugin://plugin.video.youtube/play/?${q['list']?'playlist_id='+q['list']:'video_id='+q['v']}`,p=prompt('',v||(document.getElementById('jp_audio_0')||{}).src||'https://s3.amazonaws.com/cnn-assets/app-assets/cnn-lite/liteaudio.m3u8'),u=p&&`http://${ip}/jsonrpc?request={"jsonrpc":"2.0","id":1,"method":"Player.Open","params":{"item":{"file":"${encodeURIComponent(p)}"}}}`,z=u&&(document.head.appendChild(document.createElement('video')).src=u) | |
var isDigit = testValue/10<1?true:false; | |
var largestNumber = arrayOfNumbers.sort(function(a,b)b-a)[0]; //ok in firefox | |
var largestNumber = arrayOfNumbers.sort((a,b)=>b-a)[0]; // ES6 | |
var largestNumber = Math.max.apply(Math, arrayOfNumbers); // ES5 | |
var largestNumber = Math.max(...arrayOfNumbers); // ES6 | |
var random24bitColor = '#'+Math.random().toString(16).slice(-6); | |
var random12bitColor = '#'+Math.random().toString(16).slice(-3); | |
var random_8bitColor = '#000'.replace(/0/g,function(){return '0369cf'.split('')[Math.random()*6|0]}); //ES5 | |
var random_8bitColor = '#000'.replace(/0/g,f=>'0369cf'[Math.random()*6|0]); //ES6 | |
var random_8bitColor = '#000'.replace(/0/g,f=>51*(Math.random()*6|0)); //ES6 | |
var random_8bitAlpha = 'rgba(0,0,0,.5)'.replace(/0/g,f=>51*(Math.random()*6|0)); //ES6 | |
var urlQueryPairsObj = location.search.substr(1).split("&").reduce((o,i)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v),o),{}); //ES6 | |
var urlQueryPairsObj = location.search.substr(1).split("&").reduce((o,i,u,k,v)=>(u=decodeURIComponent,[k,v]=i.split("="),o[u(k)]=v&&u(v),o),{}); //proper ES6 | |
var uuid = (a=0,b='')=>{while(++a<36)b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-';return b}; //https://jsperf.com/uuid-generator-one-liners | |
var strComp = s1 === s2 ? 0 : s1 > s2 ? 1 : -1; | |
function superClick(node) { | |
for (let eventType of ['mouseover', 'mousedown', 'mouseup', 'click']) | |
node.dispatchEvent(new MouseEvent(eventType,{view: window, bubbles: true, cancelable: true})) | |
} | |
// -OR - | |
$0.__proto__.superClick = function() { | |
for (let eventType of ['mouseover', 'mousedown', 'mouseup', 'click']) { | |
this.dispatchEvent(new MouseEvent(eventType,{view: window, bubbles: true, cancelable: true})) | |
} | |
/*v1*/ | |
function dom(d, o, m) { | |
m = m || window.document; | |
o = o === 'ALL' ? true : false; | |
return ((a,b)=>o && m[a] && m[a](d).length && m[a](d) || m[b] && m[b](d) || !o && m[a] && m[a](d) || "")(o ? 'querySelectorAll' : 'querySelector', o ? 'getElementsByClassName' : 'getElementById'); | |
} | |
/*v2*/ | |
function dom(d, o, m) { | |
m = m || window.document; | |
o = o === 'ALL' ? true : false; | |
return ((a,b)=>o && m[a] && m[a](d).length && m[a](d) || m[b] && m[b](d) || m[a] && m[a](d) || "" | |
)(o ? 'querySelectorAll' : 'querySelector', o ? 'getElementsByClassName' : 'getElementById'); | |
} | |
console.log(dom('div', 'ALL')); | |
// set favicon | |
with(document.head.appendChild(document.createElement('link'))) {rel='shortcut icon'; href='/favicon.ico';} | |
(x=>[x.rel,x.href]=['shortcut icon','/favicon.ico'])(document.head.appendChild(document.createElement('link'))); | |
(x=>{x.rel='shortcut icon';x.href='/favicon.ico';})(document.head.appendChild(document.createElement('link'))); | |
// insert a css rule | |
with(document.styleSheets[0]) {insertRule('body{display:none}', cssRules.length);} | |
(x=>x.insertRule('body{display:none}',x.cssRules.length))(document.styleSheets[0]); | |
// append and execute script | |
document.head.appendChild(document.createElement('script')).textContent = '(window.popup=window.open()).document.open().close()'; | |
document.head.appendChild(document.createElement('script')).src = 'data:application/javascript,alert("pizza")'; | |
document.head.appendChild(document.createElement('script')).src = 'data:,alert("pizza")'; | |
// object literal as switch statement | |
({ case1: ()=> 'one', | |
case2() {return 'two';}, | |
case3: f=> {return 'three';}, | |
case4: function() {return 'four';}, | |
'case5': function() {return 'five';}, | |
default() {return 'default';}, | |
switch(x) {return (this[x] || this.default)();} | |
}).switch('case3'); | |
for (let [name, builder] of Object.entries(models)) { //ES6 destructuring | |
// do something | |
} | |
String.prototype.toTitleCase = function () {return this.replace(/([^/0-9\s:-])([^/\s:-]*)/g, ($0,$1,$2) => $0.match(/^(?:von|van|der|du|de)$/) || $0.match(/^['A-Z]a?c?['A-Z]+[a-z]*$/) && /[a-z]/.test(this) || /[0-9]/.test(this.charAt(this.indexOf($0)-1)) ?$0 : $0.toLowerCase().match(/^(?!mr|jr|sr|ln|st|dr|pl|rd)(?:..|afb)$/) ? $0.toUpperCase() : $1.toUpperCase() + $2.toLowerCase())}; | |
String.prototype.toTitleCase = function () { | |
return this.replace( | |
/([^0-9\s.:-])([^\s.:-]*)/g, | |
($0, $1, $2) => | |
$0.match(/^(?:von|van|der|du|de)$/) || //use as-is | |
$0.match(/^['A-Z]+$/) && /[a-z]/.test(this) || //use as-is if word is all 'CAPS && string has also lower case | |
/[0-9]/.test(this.charAt(this.indexOf($0)-1))?$0: //use as-is if this is preceded by a number; allows 123B and 21st | |
$0.toLowerCase().match(/^(?!mr|dr|st|ct|mt)(?:..|afb)$/) ? $0.toUpperCase() : //excluding some 2-char combos, | |
//if 2-chars||Afb, use all uppercase | |
$1.toUpperCase() + $2.toLowerCase() // all other cases, capitalize first letter | |
) | |
}; | |
//IIAF | |
(() => { | |
return 123 | |
})(); //<< semicolon! | |
My solution to the loss of 'with' statements is to use IIAAFs (immediately invoked anonymous arrow functions). They offer decent readability and syntactic sugar with better performance: | |
<pre>with( document.head.appendChild(document.createElement('link')) ) { | |
rel = 'shortcut icon'; | |
href = 'https://assets-cdn.github.com/favicon.ico'; | |
}</pre> | |
...becomes... | |
<pre>(x => { | |
x.rel = 'shortcut icon'; | |
x.href = 'https://assets-cdn.github.com/favicon.ico'; | |
})( document.head.appendChild(document.createElement('link')) );</pre> | |
/* object literal pattern */ | |
var bob = { | |
name: 'Bob', | |
'race': 'white', | |
123: 456, | |
about: this.name + ' is ' + this.race, //this===window!! | |
sayHi: function () {return 'Hi, I am ' + this.name}, | |
sayBye: () => {return this.name + ' see ya!'}, //this===window!! | |
sayWho () {return this.name + ' is who'}, | |
get initial () {return this.name.charAt(0)}, | |
set setName (v) {this.name = v}, | |
} | |
bob.name; //Bob | |
bob['race'] //white | |
bob[123]; //456 | |
bob.about; // is undefined | |
bob.sayHi(); //Hi, I am Bob | |
bob.sayBye(); // see ya! | |
bob.sayWho(); //Bob is who | |
bob.initial; //B | |
bob.setName = 'Robert'; | |
/* constructor pattern */ | |
function Person(name) { | |
if (!(this instanceof Person)) | |
return new Person(...arguments); | |
this.name = name; | |
this.sayHi = function(){ | |
return 'Hi, I am ' + this.name; | |
} | |
} | |
/* module patterns */ | |
var MY_MODULE = (function(public,global,$,undefined){ | |
var settings = { | |
indicator : 'on', | |
expanded : 'no', | |
isCool : true, | |
}, | |
privateVar = 1, | |
_end_; | |
function privateFunc1(){ /***/ } | |
function privateFunc2(){ /***/ } | |
public.init = function(){ /***/ }; | |
public.moduleMethod = function(){ /***/ }; | |
public.moduleProperty = 1; | |
return public; | |
}(MY_MODULE || {},window,jQuery)); | |
var MY_MODULE2 = (function(public,global,$,undefined){ | |
var settings = { }, | |
privateVar = 1, | |
_end_; | |
function privateFunc1(){ /***/ } | |
function privateFunc2(){ /***/ } | |
Object.assign(public, { | |
init : function(){ /***/ }, | |
moduleMethod : function(){ /***/ }, | |
moduleProperty : 1, | |
}); | |
return public; | |
}(MY_MODULE2 || {},window,jQuery)); | |
var MY_MODULE3 = (function(public,global,$,undefined){ | |
var settings = { }, | |
privateVar = 1, | |
_end_; | |
var privateFunc1 = function(){ /***/ }; | |
var privateFunc2 = function(){ /***/ }; | |
var init = function(){ /***/ }; | |
var publicMethod = function(){ /***/ }; | |
var publicProperty = 1; | |
Object.assign(public, { | |
init : init, | |
publicMethod : publicMethod, | |
publicProperty : publicProperty, | |
}); | |
return public; | |
}(MY_MODULE3 || {},window,jQuery)); | |
var MY_MODULE4 = (function(global,$,undefined){ | |
var _settings = { }, | |
_privateVar = 1, | |
_end_; | |
var _privateFunc1 = function(){ /***/ }; | |
var _privateFunc2 = function(){ /***/ }; | |
var init = function(){ /***/ }; | |
var publicMethod = function(){ /***/ }; | |
var publicProperty = 1; | |
return { | |
init : init, | |
publicMethod : publicMethod, | |
publicProperty : publicProperty, | |
}; | |
}(window,jQuery)); | |
var MY_MODULE5 = (function(public,global,$,undefined){ | |
var _settings = { }, | |
_privateVar = 1, | |
_end_; | |
var _privateFunc1 = function(){ /***/ }; | |
var _privateFunc2 = function(){ /***/ }; | |
var init = function(){ /***/ }; | |
var publicMethod = function(){ /***/ }; | |
var publicProperty = 1; | |
public.init = init; | |
public.publicMethod = publicMethod; | |
public.publicProperty = publicProperty; | |
return public; | |
}; | |
}(MY_MODULE5 || {},window,jQuery)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment