Skip to content

Instantly share code, notes, and snippets.

@mortoray
Last active February 7, 2018 13:36
Show Gist options
  • Save mortoray/077f8904551ff1f9c08ab86933f71967 to your computer and use it in GitHub Desktop.
Save mortoray/077f8904551ff1f9c08ab86933f71967 to your computer and use it in GitHub Desktop.
JavaScript Cheat Sheet

JavaScript Cheat Sheet

Class Members

class Tuxedo {
	constructor( args ) { 
		this.propName = someValue
	}
	
	instanceFunction() { ... }
	
	static staticFunction() { ... }
	
	get propertyName() {
		return theValue
	}
	
	set propertyName(theValue) { ... }
}

Exports

Default

export default class MyModel { ... }
import any_name from './MyModel'

Non-Defaults

export class MyClass { ... }
export function floof() { ... }
import { MyClass, floof } from './Stuff'
import * as stuff from './Stuff'

Iterate by key in object

var factionsList = []
for (var m in factions) {
	factionsList.push( factions[m] )
}

WARNING: Don't use for arrays.

Iterate over array elements/strings/sets

for (const item of iterable) { ... }
for (const codePoint of string) { ... }

Bound iteration

for (let i = 0; i  < someSize; ++i) { ... }

Array to Indexed Object

var rawTypes = require("Netrunner/types")
var types = rawTypes.data.reduce( (obj, type) => { 
	obj[type.code] = type
	return obj
}, {})

Filter Array

filtered = items.filter( item => boolExpr(item) )

Sort Array

sorted = items.sort( (a,b) => a - b )

Fetch

fetch( url ).then( (resp) => {
	return response.json()
}).then( (data) => {
	//handle data
}).catch( (err) => {
	console.log( err.message )
})

Unicode

Warning: Some JS functions work with broken UCS-2. Iterables however work with code points.

Should work as-is in strings (utf8 file encoding)

'\uABCD'
'\u{ABCDE}'

map

var mapped = someArray.map( x => expr(x) )

fold

var total = someArray.reduce( (prev,next) => prev + next )

Also reduceRight

Variable arguments

function mult( ...theValues ) {
	return theValues.reduce( (p,c) => {
		return p * c
	})
}

Add/Remove array items

arr.push( valueAtEnd )
arr.splice( index, 0, insert@Index )
var arrOfRemoved = arr.splice( index, 1 )  //remove 1 item at index
var firstItem = arr.shift()
var lastItem = arr.pop()
var subArr = arr.slice( startIndex [, endIndex] )
var copy = arr.slice()

Search Array

//-1 if not found, also `lastIndexOf` 
var index = arr.findIndex( (element [, index]) => boolExpr() )
var value = arr.find( (elemen [, index]) => boolExpr() )
var yesNo = arr.includes( value [, startIndex])

Join

var list = arrItems.join( "-" )

Create Range

num5_14 = Array.from(new Array(10), (x,i) => i + 5)
num0_9 = [...Array(10).keys()]
charsA_D = Array.from(new Array(5), (x,i) => String.fromCharCode('A'.charCodeAt(0) + i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment