Skip to content

Instantly share code, notes, and snippets.

@NullDev
Last active June 7, 2025 18:08
Show Gist options
  • Save NullDev/1071817d426371f441dd9f28ef3d7fba to your computer and use it in GitHub Desktop.
Save NullDev/1071817d426371f441dd9f28ef3d7fba to your computer and use it in GitHub Desktop.
Random JS Snippets I made. Util, Weird stuff, Random...
// Global Chain function example with prototyping
Function.prototype.test = function(x){
var arg1 = this();
var arg2 = x;
console.log(
"Arg1: " + arg1 +
"\nArg2: " + arg2
);
}
function x(){
return "arg1";
}
x.test("arg2");
// Should output:
// Arg1: arg1
// Arg2: arg2
// https://jsfiddle.net/vc6kysmL/
let obj = { lol: [{}, {a: "aa", b: "bb", c: "cc"}] };
obj.lol?.[({ lol: [, { a: x2, b: y2, c: z2 }] } = obj) && console.log(x2, y2, z2)];
import { OrbitControls } from "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js";
// Fibonacci Sphere
// DEMO: https://codepen.io/nldev/pen/xbGLNRO
const numberOfPoints = 1500;
const radiusOfSphere = 30;
const getFibonacciSpherePoints = function(samples = 1, radius = 1){
const points = []
const offset = 2 / samples
const increment = Math.PI * (3 - Math.sqrt(5));
for (let i = 0; i < samples; i++) {
let y = ((i * offset) - 1) + (offset / 2);
let distance = Math.sqrt(1 - Math.pow(y, 2));
let phi = ((i + 1) % samples) * increment;
let x = Math.cos(phi) * distance;
let z = Math.sin(phi) * distance;
x *= radius;
y *= radius;
z *= radius;
points.push({ x, y, z });
}
return points;
};
const initSceneAndAddFibonacciSphere = function(fibonacciSpherePoints){
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xffffff, 70, 135);
scene.background = new THREE.Color(0xffffff);
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 500);
camera.position.set(0, 0, 100);
camera.lookAt(new THREE.Vector3(0, 0, 0));
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const controls = new OrbitControls(camera, renderer.domElement);
controls.screenSpacePanning = true;
controls.target.set( 0.0, 1.0, 0.0 );
controls.update();
for (let i = 0; i < fibonacciSpherePoints.length; i++){
const point = fibonacciSpherePoints[i];
const geometry = new THREE.SphereGeometry(0.2);
const material = new THREE.MeshBasicMaterial({ color: 0x59673C });
const sphere = new THREE.Mesh(geometry, material);
sphere.position.x = point.x;
sphere.position.y = point.y;
sphere.position.z = point.z;
scene.add(sphere);
}
renderer.render(scene, camera);
function animate(){
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update();
}
animate();
};
initSceneAndAddFibonacciSphere(getFibonacciSpherePoints(numberOfPoints, radiusOfSphere));
Array.apply([], Array(100)).map((e, i) => [["fizz"][i % 3], ["buzz"][i % 5]].join("") || i);
/**
* This basically allows expressions like 3 > 2 > 1
* which is usually written as 3 > 2 && 2 > 1
*
* I basically did this because I wanted to see how easy it is
* to implement such "new syntax" in JS
*
* Please don't use this. It's hacky.
*/
let lastRightHandOperator = null;
Number.prototype[">"] = Boolean.prototype[">"] = function(x){
if (isNaN(parseFloat(this))){
let cache = lastRightHandOperator;
lastRightHandOperator = this;
return (this && cache > x);
}
lastRightHandOperator = this;
return this > x;
};
console.log(
8 [">"] (5) [">"] (3)
);
// true
console.log(
3 [">"] (5) [">"] (3)
);
// false
// Reference code for anti cheat bypass methods
try {
(_)(_); // lol
}
// We throw an exception because it's easier to hide our calls in the stack
catch (e){
// Conceal callee in catch
try {
let isRecurrent = e.stack.match((new RegExp("kloader", "g"))).length > 1;
// Load out script from the chrome runtime via XHR
if (!isRecurrent) inject(loadScriptCode(chrome.runtime.getURL("").match(/\/\/(\w{9})\w+\//)[1]));
} catch (__e){
// Pass on actual exceptions so it's not suspicious
if (__e instanceof DOMException) console.warn(e);
else throw __e;
}
}
// Manage our internal state
const shared = new Map(Object.entries({ f2h: new WeakMap(), s2h: [], hg: [] }));
// hg -> hidden globals
let hideDef = (obj, key, value) => {
shared.get("hg").push(key);
// prevent others from reading out all props
Object.defineProperty(obj, key, { enumberable: false, configurable: false, writable: true, value: value });
};
if (!_window.top[0]) hideDef(_window.top, "kload", sharedState);
// f2h -> func to hide
let hideFunc = (init, h00ked) => shared.get("f2h").set(h00ked, init);
// s2h -> str to hide
let hideStr = (initstr, h00kstr) => shared.get("s2h").push({
from: new RegExp(h00kstr.replace(/([\[|\]|\(|\)|\*|\\|\.|\+])/g, "\\$1"), "g"), to: initstr
});
// hide variables from window by proxying getOwnPropertyDescriptors
const __GOPD = _window.Object.getOwnPropertyDescriptors;
let hook__GOPD = new Proxy(__GOPD, {
apply: function(target, _this, _arguments){
try {
// hoist `var` out of try
var desc = Function.prototype.apply.apply(target, [_this, _arguments]);
} catch (e) {
// hide proxy in stacktrace
e.stack = e.stack.replace(/\n.*Object\.apply \(<.*/, "");
throw e;
}
for (let i = 0; i < shared.get("hg").length; i++) delete desc[shared.get("hg")[i]];
return desc;
}
});
_window.Object.getOwnPropertyDescriptors = hook__GOPD;
// hook window.open to always return null
// otherwise we would have to also patch native functions in new window
const __open = _window.open;
let hook__open = new Proxy(__open, {
apply: function(target, _this, _arguments) {
try {
let ret = Function.prototype.apply.apply(target, [_this, _arguments]);
} catch (e) {
// modify stack trace to hide proxy
e.stack = e.stack.replace(/\n.*Object\.apply \(<.*/, '');
throw e;
}
return null;
}
});
_window.open = hook__open;
const handler = {
apply: function(target, _this, _arguments){
try {
var original_fn = Function.prototype.apply.apply(target, [_this, _arguments]);
} catch (e) {
e.stack = e.stack.replace(/\n.*Object\.apply \(<.*/, '');
throw e;
}
if (_arguments.length == 2 && _arguments[1].length > 1337) {
// keep ref to original
let script = _arguments[1];
// anti anti chet & anti skid (we don't want to risk running on newer versions)
const version = script.match(/\w+\['exports'\]=(0[xX][0-9a-fA-F]+);/)[1];
if (version !== "0x17e87") if (version !== "0x17e87") _window[document.write("Version mismatch: " + version);
// ...
// Cheats ...
// ...
const code_to_overwrite = script.match(/(\w+\['\w+'\]&&\(\w+\['\w+'\]=\w+\['\w+'\],!\w+\['\w+'\]&&\w+\['\w+'\]\(\w+,\w*1\)\),\w+\['\w+'\]=\w*0,\w+\['\w+'\]=\w*0),!\w+\['\w+'\]&&\w+\['\w+'\]\['push'\]\(\w+\),\w+\['\w+'\]\(\w+,\w+,!\w*1,\w+\['\w+'\]\)/)[1];
let callLock = `top['kload'].get('locked')(` + ..._window[1].params + `)`;
// pad to avoid stack trace line:column number detection.
// the script will have the same length as it originally had.
// this hook is also placed before the anti cheat loads.
if (callLock.length + 4 > code_to_overwrite.length) throw "Target too small: " + [callLock.length, code_to_overwrite.length];
let whitespaces = code_to_overwrite.match(/\s/g);
for (var i = 0; i < whitespaces && whitespaces.length; i++) callLock += whitespaces[i];
callLock += " ";
while (callLock.length < code_to_overwrite.length - 2) callLock += ' ';
callLock += " ";
script = script.replace(code_to_overwrite, callLock);
const realScript = _arguments[1];
_arguments[1] = script;
let mod_fn = Function.prototype.apply.apply(target, [_this, _arguments]);
_arguments[1] = realScript;
return mod_fn;
}
return original_fn;
}
}
// Override fn constructor
const realFunction = _window.Function;
let hookedFunction = new Proxy(realFunction, handler);
_window.Function = hookedFunction;
'use strict';
class GameLoader {
observe(){
return new Promise(resolve => {
var observer = new MutationObserver((mutations, observer) => {
for(let mutation of mutations){
for(let node of mutation.addedNodes){
if(node.tagName == 'SCRIPT' && node.textContent.includes('Yendis Entertainment')){
console.info('Got the WASM loader script:', node);
// Clear the script's textContent to prevent loading.
node.textContent = '';
console.info('WASM loader removed');
// Resolve the promise to indicate the game is ready to load.
resolve();
// The observer no longer needs to check for new elements because the WASM loading has been stopped.
observer.disconnect();
}
}
}
});
observer.observe(document, {
childList: true,
subtree: true,
});
});
}
async client_key(){
// Make the request
var client_key_request = await fetch('https://api.sys32.dev/v2/key');
// Read the response as text.
return await client_key_request.text();
}
async matchmaker_token(client_key){
// Attach the header.
var hash_options = {
headers: new Headers(),
};
hash_options.headers.set('Client-Key', client_key);
// Make the request
var token_request = await fetch('https://matchmaker.krunker.io/generate-token', hash_options);
// Read the response as JSON.
return await token_request.json();
}
async hash_token(token){
// This endpoint requires the token as input so we will make a POST request.
var hash_options = {
method: 'POST',
headers: new Headers(),
};
// Set the Content-Type to application/json otherwise the server will not accept JSON input
hash_options.headers.set('Content-Type', 'application/json');
// Turn the object into a string appropiate for the fetch body
hash_options.body = JSON.stringify(token);
// Make the request
var hash_request = await fetch('https://api.sys32.dev/v2/token', hash_options);
// Read the response as JSON
return await hash_request.json();
}
async token_argument(){
// Retrieve the Client-Key header.
var client_key = await this.client_key();
console.info('Retrieved Client-Key:', client_key);
// Retrieve the matchmaker token
var token = await this.matchmaker_token(client_key);
console.info('Retrieved token:', token);
// Generate a hashed token
return await this.hash_token(token);
}
async source(){
// Make the request
var game_request = await fetch('https://api.sys32.dev/v2/source');
// Read the response as text
return await game_request.text();
}
};
var loader = new GameLoader();
// Observe for the WASM loader without waiting for it
// In the time it takes to finish observing, we will have the token argument and game source ready
var load_promise = loader.observe();
var token_argument = loader.token_argument();
loader.source().then(async game_code => {
var hash = Math.random().toString();
// remove '0.'
hash = hash.slice(2);
// suffix
hash = '_' + hash;
// The game will see the hash variable as a reference to this object.
var data = {
// A callback the game will call with the game variable
handle_game(game){
// { players: {...} }, [ ...Player ]
console.log(game, game.players.list);
// Finding the local player every second
setInterval(() => {
for(let entity of game.players.list){
// isYTMP = isYou
if(entity.isYTMP){
// The local player's alias is: Guest_6
console.log('The local player\'s alias is:', entity.alias);
break;
}
}
}, 1000);
}
};
console.log('Hash generated', hash, data);
console.info('Retrieved the games source, the length is', game_code.length);
// Apply various patches before creating the game function
game_code = game_code.replace(
/(\w+)\.moveObj=func/,
// Hooking when the game defines the property moveObj (which is only on the game object)
// The game function on data is called with game as an argument.
(match, game) => `${hash}.handle_game(${game}),${match}`
);
// Create the game function
var game_function = new Function(hash, 'WP_fetchMMToken', game_code);
// Wait for the WASM loader to be added to the document because its also when libraries such as zip.js are loaded.
await load_promise;
// The game recieves WP_fetchMMToken as a promise, we do not await for the argument when calling the game function.
// Call the function using the data variable
game_function(data, token_argument);
console.info('Retrieved token:', await token_argument);
console.info('Krunker loaded.');
});
// https://jsfiddle.net/NullDev/q8sd3y7u/1/
const validate = function(e){
const segments = document.getElementById("txt").value.split(".");
const res = document.getElementById("res");
res.innerHTML += "IP: ";
(segments.length < 4)
? res.innerHTML += `<font color="#FF0000">${segments.join(".")}</font>`
: segments
.map((e, i) => Number(!isNaN(e) && e >= 0 && e <= 255 && i <= 3))
.forEach((e, i) => res.innerHTML += `<font color="#${!!e ? "00FF00" : "FF0000"}">${segments[i]}</font>${(i < (segments.length - 1)) ? "." : ""}`);
res.innerHTML += "<br>";
};
// Smol pi approximation in JS
for(i=p=2;i<1e6;i+=2)p*=i*i/(i*i-1);console.log(p)
// My solution for the "Pisano Period - Performance Edition" CodeWars Challange
// https://www.codewars.com/kata/65de16794ccda6356de32bfa
const gcd = (a, b) => {
while (b) [a, b] = [b, a % b];
return a;
};
const lcm = (a, b) => a / gcd(a, b) * b;
// Fast-doubling Fibonacci (returns [F(n), F(n+1)] mod m)
// https://www.nayuki.io/page/fast-fibonacci-algorithms
const fibPair = function(n, m){
let a = 0n; let b = 1n;
for (let bit = BigInt(n.toString(2).length - 1); bit >= 0n; bit--){
const d = (a * ((b * 2n % m) - a + m)) % m;
const e = (a * a + b * b) % m;
[a, b] = ((n >> bit) & 1n) ? [e, (d + e) % m] : [d, e];
}
return [a, b];
};
const modPow = function(base, exp, mod){
let res = 1n;
for(;exp; exp >>= 1n){
if (exp & 1n) res = res * base % mod;
base = base * base % mod;
}
return res;
};
// Miller–Rabin on 64-bit-size BigInts (deterministic base set)
// https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
const isPrime = function(n){
if (n < 2n) return false;
for (const p of [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n]){if (n === p) return true; else if (n % p === 0n) return false;}
let d = n - 1n; let s = 0n; while (!(d & 1n)){d >>= 1n; s++;}
const bases = [2n, 3n, 5n, 7n, 11n];
Witness: for (const a of bases){
if (a % (n - 1n) === 0n) continue;
let x = modPow(a, d, n);
if (x === 1n || x === n - 1n) continue;
for (let r = 1n; r < s; r++){
x = x * x % n;
if (x === n - 1n) continue Witness;
}
return false;
}
return true;
};
// Pollard-ρ (Brent variant)
// https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
const rho = function(n){
if (n % 2n === 0n) return 2n;
if (isPrime(n)) return n;
const f = (x, c, n) => (x * x + c) % n;
while (true){
let x = 2n; let y = 2n;
const c = BigInt(Math.floor(Math.random() * 10) + 1);
let d = 1n;
while (d === 1n){
x = f(x, c, n);
y = f(f(y, c, n), c, n);
d = gcd((x > y ? x - y : y - x), n);
}
if (d !== n) return d;
}
};
// factorisation
const factor = function(n, res = new Map()){
if (n === 1n) return res;
if (isPrime(n)){
res.set(n, (res.get(n) || 0n) + 1n);
return res;
}
const d = rho(n);
factor(d, res) && factor(n / d, res);
return res;
};
// Prime-level Pisano
const primePisano = function(p){
if (p === 2n) return 3n;
if (p === 5n) return 20n;
// Bound (Euler criterion)
// https://en.wikipedia.org/wiki/Euler%27s_criterion
const sqrt5Residue = modPow(5n, (p - 1n) / 2n, p);
const bound = (sqrt5Residue === 1n) ? p - 1n : 2n * (p + 1n);
const f = Array.from(factor(bound)).map(([pr, e]) => [pr, Number(e)]);
const divisors = [1n];
for (const [pr, e] of f){
const len = divisors.length;
let pw = 1n;
for (let i = 1; i <= e; i++){
pw *= pr;
for (let j = 0; j < len; j++) divisors.push(divisors[j] * pw);
}
}
divisors.sort((x, y)=> Number(x - y));
for (const d of divisors){
const [f0, f1] = fibPair(d, p);
if (f0 === 0n && f1 === 1n) return d;
}
return 0n;
};
// https://en.wikipedia.org/wiki/Pisano_period
function pisanoPeriod(n){
const n_ = BigInt(n);
if (n_ === 1n) return 1n;
const primeFactors = factor(n_);
let period = 1n;
for (const [p, e] of primeFactors) period = BigInt(lcm(period, primePisano(p) * (p ** (e - 1n))));
return period;
}
// ES6 way of generating a random string with variable length
let getRandomString = (length) => [...Array(length)].map(() => Math.random().toString(36)[2]).join("");
let str = getRandomString(10);
// -> 225n9b53x6
// ---
// Demo: https://jsfiddle.net/fku9y6sm/
// A weird implementation of PHP's Spaceship operator in JavaScript
Number.prototype["<=>"] = function(x){
return Math.sign(this - x);
}
var result = 5 ["<=>"] `4`;
console.log(result);
// https://jsfiddle.net/veyar51m/
function sq(A){
let B = A / 2;
let p = 0;
let i = 0;
for (;;){
++i;
B = A / B + B;
B = B / 2;
if (p == B){
console.log("Took " + i + " iterations.");
return B;
}
p = B;
}
}
console.log("C_SOL", sq(2500));
console.log("M_SOL", Math.sqrt(2500));
console.log("C_SOL", sq(9297482682382.872753537));
console.log("M_SOL", Math.sqrt(9297482682382.872753537));
console.log("C_SOL", sq(1));
console.log("M_SOL", Math.sqrt(1));
console.log("C_SOL", sq(0));
console.log("M_SOL", Math.sqrt(0));
window.__defineGetter__("a", () => {
if (typeof i === "undefined"){
i = 0;
}
i = (i % 2 === 0) ? 1 : ++i;
return i;
});
a = 1
b = "1"
console.log(a == b); // true
console.log(a == b); // false
console.log(a == b); // true
console.log(a == b); // ...
console.log(a == b);
// ...
// another one
let{log:l}=console,x=0;console.log=_=>l(!x++);
a = 1
b = "1"
console.log(a == b);
console.log(b == a);
// https://jsfiddle.net/NullDev/hf1meuzt/6/
const sleep = ms => new Promise((res) => setTimeout(res, ms));
const typeWrite = async function(input_text, speed = 70){
for (const char of input_text){
document.getElementById("game_output").innerHTML += char;
await sleep(speed);
}
};
const newGame = function(){
typeWrite("A man approaches you...");
}
newGame();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment