Skip to content

Instantly share code, notes, and snippets.

@Offirmo
Last active February 22, 2024 04:06
Show Gist options
  • Save Offirmo/fd701275e56a0f56533fd33e1b9eb2ba to your computer and use it in GitHub Desktop.
Save Offirmo/fd701275e56a0f56533fd33e1b9eb2ba to your computer and use it in GitHub Desktop.
[JS Hacker Rank useful snippets] #JavaScript #competition
const _ = require('lodash')
/////// REDUCE ///////
res = .reduce((acc, val) => {
return acc + val
}, 0)
err = decorators.reduce((err, decorator) => {
return decorator(err)
}, err)
_.uniq()
_.union()
_.intersection()
_.difference()
_.groupBy([6.1, 4.2, 6.3], Math.floor)
_.partition()
_.memoize(func, [resolver])
// parse input
const [ l1, l2 ] = input.split('\n')
const numbers = l2.split(' ')
// fast arrays
let s = input.trim()
const u8in = Uint8Array.from(s, (c, i) => s.charCodeAt(i))
const u8temp = u8in.slice(0)
console.log(String.fromCharCode(...u8out))
// number to formatted string
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
var num = 12345.6789
// # of digits after decimal point
num.toFixed() // '12346' rounding, no fractional part
num.toFixed(1) // '12345.7' rounding
num.toFixed(6) // '12345.678900' added zeros
(1.23e+20).toFixed(2) // '123000000000000000000.00'
var num = 12345.6789
// # of significant digits overall
num.toPrecision() // '12345.6789' no change
num.toPrecision(5) // '12346' rounded
num.toPrecision(2) // '1.2e+4'
num.toPrecision(1) // '1e+4'
number.toExponential // .e+.
// left shift
const p1 = a.slice(0, k)
const p2 = a.slice(k)
p1.unshift(...p2)
console.log(p1.join(' '))
// set
const seen = new Set()
seen.add(1)
mySet.has(1)
// Math
Math.abs(-5) // 5
Math.sign( 3) // 1
Math.sign(-3) // -1
Math.sign( 0) // 0
Math.max(1, 2, 3)
let max_ = Number.NEGATIVE_INFINITY
max_ = Math.max(max_ , )
Math.min(1, 2, 3)
let min_ = Number.POSITIVE_INFINITY
min_ = Math.min(min_ , )
Math.pow(2, 8) // 256
Math.ceil( .95) // 1
Math.ceil( 3) // 3
Math.ceil(-0.95) // -0
Math.ceil(-3) // -3
Math.floor( 3.95) // 3
Math.floor( 4 ) // 4
Math.floor(-5.05) // -6
Math.round( 20.49) // 20
Math.round( 20.5) // 21
Math.trunc(13.37) // 13
Math.trunc(0.123) // 0
Math.trunc(-0.123) // -0
Math.fround(0) // 0
Math.fround(1) // 1
Math.fround(1.337) // 1.3370000123977661
Math.fround(1.5) // 1.5
// 32 bits
Math.imul(0xffffffff, 5) // -5
Math.clz32(1) // 31 "count leading zeros"
Math.clz32(1000) // 22
Math.clz32(true) // 31
// fast arrays
var uint8 = new Uint8Array(2);
uint8[0] = 42;
Uint8ClampedArray
// misc
Number.EPSILON
Number.NEGATIVE_INFINITY
Number.POSITIVE_INFINITY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment