Skip to content

Instantly share code, notes, and snippets.

@neopunisher
Last active February 15, 2023 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neopunisher/670ff23ebdba163106d9a415203d0c05 to your computer and use it in GitHub Desktop.
Save neopunisher/670ff23ebdba163106d9a415203d0c05 to your computer and use it in GitHub Desktop.
// String stuff
const encodeStr = (str)=>new TextEncoder().encode(str)
const strLen = (str)=> encodeStr(str).length
const stoa = (str)=>Uint8Array.from(str, x => x.charCodeAt(0))
const atos = (arr)=>String.fromCharCode.apply(null, arr)
// Base 2 stuff
const getBaseLog = (x, y) => (Math.log(y) / Math.log(x))
const baseTwoLog = (y) => getBaseLog(2,y)
const powTwo = (x)=>Math.pow(2,x)
// byte stuff
const byteLen = powTwo(3);
const maxBufferLen = powTwo(31)-powTwo(21);
const maxIntOfBytes = (i)=>(powTwo(i*8)-1)
const littleEndian = (() => {
const buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
// Int16Array uses the platform's endianness.
return new Int16Array(buffer)[0] === 256;
})();
console.log(littleEndian); // true or false
//bit stuff
const toBits = (idx)=>(idx >>> 0).toString(2).padStart(8,'0')
const maxIntOfBits = (i)=>(powTwo(i)-1)
const byteToBin = (idx)=>((idx >>> 0).toString(2).padStart(8,'0'))
// sizes
const pageSize = powTwo(12);
const onekb = powTwo(10);
const onemb = powTwo(20);
const onegb = powTwo(30);
// hex
const hexDigit = (b)=>b.toString(16).padStart(2, '0')
const bufToHex = (buf)=>Array.from(new Uint8Array(buf)).map(hexDigit).join('')
//jsimport
const importJs = async (url, module = {exports:{}}) =>
(Function('module', 'exports', await (await fetch(url)).text()).call(module, module, module.exports), module).exports
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment