JavaScript

From David's Wiki
Revision as of 13:24, 24 January 2020 by David (talk | contribs) (→‎mathjs)
\( \newcommand{\P}[]{\unicode{xB6}} \newcommand{\AA}[]{\unicode{x212B}} \newcommand{\empty}[]{\emptyset} \newcommand{\O}[]{\emptyset} \newcommand{\Alpha}[]{Α} \newcommand{\Beta}[]{Β} \newcommand{\Epsilon}[]{Ε} \newcommand{\Iota}[]{Ι} \newcommand{\Kappa}[]{Κ} \newcommand{\Rho}[]{Ρ} \newcommand{\Tau}[]{Τ} \newcommand{\Zeta}[]{Ζ} \newcommand{\Mu}[]{\unicode{x039C}} \newcommand{\Chi}[]{Χ} \newcommand{\Eta}[]{\unicode{x0397}} \newcommand{\Nu}[]{\unicode{x039D}} \newcommand{\Omicron}[]{\unicode{x039F}} \DeclareMathOperator{\sgn}{sgn} \def\oiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x222F}\,}{\unicode{x222F}}{\unicode{x222F}}{\unicode{x222F}}}\,}\nolimits} \def\oiiint{\mathop{\vcenter{\mathchoice{\huge\unicode{x2230}\,}{\unicode{x2230}}{\unicode{x2230}}{\unicode{x2230}}}\,}\nolimits} \)

This page is a mostly about browser-based JavaScript or ECMAScript usage and interaction with the HTML DOM (window). For server and desktop application JavaScript usage, please see the NodeJS page.

Usage

Canvas

Video

Your HTML:

<video id="myVideoElt" controls>
</video>

Your JS:

const myVideo = document.getElementById("myVideoElt");

// Create a new source
const newSource = document.createElement("source");
const myVideoUrl = "https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm";
newSource.setAttribute("src", myVideoUrl);
myVideo.appendChild(newSource);
myVideo.play();

Regular Expressions (Regex)

Reference

var myRegex = /(\d+),(\d+)/;
var myStr = "124,52";
var match = myStr.match(myRegex);
// Captures
console.log(match[1], match[2]);
console.table(match);


Classes

Traditionally, classes are done using functions in JavaScript.

Traditional JS Classes
function Rectangle(height, width) {
  this.height = height;
  this.width = width;
}

// To extend some Shape class
Rectangle.prototype = Object.create(Shape.prototype);
// To add to the prototype
Object.assign(Rectangle.prototype, {
  constructor: Rectangle,
  getSize: function() {
    return this.height * this.width;
  }
});

Mozilla Reference
ES2015 adds syntax for classes in JavaScript.

class Rectangle extends Shape {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }

  getSize() {
    return this.height * this.width;<br />
  }
}

Compilation

Webpack

Babel

Websockets

How to use Websockets

Getting Started

let ws = new WebSocket(this.SERVER_URL);
ws.onopen = function(event) {
   console.log("Websocket opened");
   ws.send("Hi");
};
ws.onmessage = function(event) {
   console.log("message received");
   console.log(event.data);
};
ws.onclose = function() {
   console.log("WS Closed");
};

Data Structures

JavaScript traditionally has arrays and objects (hashmap) data structures.
ES2015 (ES6) adds several collections including: Map, Set, WeakMap, WeakSet
ES6 Collections

Arrays

let arr = [1,2,3];

// Map
arr.map(x => x > 2); // [false, false, true]

// Reduce or Fold
// Note that if you do not provide an initial accumulator,
// then the first element will be your accumulator
// I.e. the first call to your function will be (arr[0], arr[1])
arr.reduce((acc, x) => acc + x, 0); // 6

Objects

Objects are maps in JavaScript. They are typically implemented as hashmaps by the JS engine.
Note that you can only use numbers and strings as keys.
Learn more about the implementation at https://v8.dev/blog/hash-code

let my_map = {};
// or my_map["my_key"]
my_map.my_key = "my_value";
"my_key" in my_map;

// Loop over keys
for (let key in a) {
  console.log("Key:", key);
}

Map

Set

WeakMap

Unlike map, weakmap holds weak references to its keys. This allows keys to be garbage collected when no reference to it remains. Note that once keys are garbage collected, they are also removed from the weakmap since you can no longer access them. You can not iterate through a weakmap.

WeakSet

Modules

Getting Started

MDN Guide to Modules

Useful Packages

Packages which run in the browser and may be useful for developing web applications. Note that some of these may overlap with the NodeJS page.

lerp, clamp

npm i lerp clamp
Math.lerp = require("lerp");
Math.clamp = require("clamp");

pako

pako github
"zlib port to javascript, very fast!"

npm install pako

url-join

Basically path.join for the browser.

npm install url-join

mathjs

https://mathjs.org/
Some useful math things for JavaScript in the browser and in NodeJS

npm install mathjs