My code golf solutions
- remove whitespace after operators when possible
- bitwise OR
|
number|0
equivalent toMath.trunc(number)
- bitwise NOT
~
- sets number to
-(number+1)
, so can be used with functions that return -1 if a 0 return is needed - coerces non-numbers to
-1
- use with
search()
(thoughmatch()
should be used oversearch()
)
- sets number to
- bitwise XOR
^
- replace
!=
with^
when comparing integers
- replace
- bracket operator
[]
Object[m='method'](arguments) // first method/property call Object[m](arguments) // subsequent calls
length of method/property | minimum calls |
---|---|
3 | 7 |
4 | 4 |
5 | 3 |
6 | 3 |
7 | 3 |
8+ | 2 |
- comma
,
- replace curly braces in conditionals and loops with commas between statements
- power
**
a**b
is equivalent toMath.pow(a,b)
- spread
...
- saves bytes when no callback is needed
- for, for in , for of
- reverse loops to remove expressions
for (a=0;a<b.length;a++) // before for (a=b.length;a--;) // after
[...array]
use spread operator when possible
- reverse loops to remove expressions
- template literals instead of parentheses when possible
isFinite()
1/number
to check instead
isNaN()
number^number
instead of isNaN(number)
Math.pow()
**
operator
Math.random()
new Date & 1
==Math.random() < .5
new Date % 330
==Math.floor(Math.random()*330)
Math.trunc()
,Math.round()
|0
bitwise OR instead
RegExp()
eval()
instead
- array
- use coercion
''+array
instead ofjoin(',')
orjoin()
- spread operator instead of
forEach()
when possible
- use coercion
- string
match()
instead ofsearch()
instead ofindexOf()
unless regex is longer than string or you need a numeric returnslice()
is always shorter than substring, canslice(-n)
to get the last n elementssplit()
use spread operator when splitting over every element
- use type specific methods to test type
type | test |
---|---|
array | pop() |
function | call() |
number | toFixed() |
string | big() |
textNode | data() |
- initialize variables in parameters of functions or loops
this
orself
instead ofwindow
- array
map()
instead ofreduce()
when possible- use elision to put values in certain indices
- boolean
!0
for true and!1
for false if you need literal boolean values, or else use 1 and 0!!
to change a value to true or!
for false
- function
- omit parentheses on
new
calls without arguments
- omit parentheses on
- Infinity
1/0
instead ofInfinity
- number
+number
instead of parsing to coerce to float or integerAeB
instead of numbers with many trailing zerosnumber|0
to cast to integer, equivalent toMath.trunc(number)
\b
for word boundaries\d
instead of[0-9]
\w
instead of[A-Za-z0-9_]