javascript

dat.GUI

dat.GUI lets you quickly add an interface to your javascript app/game that allows you to tweak options and modify values in real time. Very handy when balancing games instead of the traditional

  1. change value
  2. reload.

Here’s a cool demo of dat.GUI’s features.

should i use react or vue

https://should-i-use-react-or-vue.now.sh/

debug jest on windows

node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand

then click Inspect on the target in chrome://inspect

intercepting fetch and XHR

Intercept fetch, log the request and the response. Adapted from this.

const mockFetch = window.fetch;
window.fetch = function() {
  console.log('request', arguments);
    return new Promise((resolve, reject) => {
        mockFetch.apply(this, arguments)
            .then((response) => {
                resolve(response);
                return response.clone().json();
            })
            .then(data => console.log('data', data))
            .catch((error) => {
                console.log('error', error);
                reject(error);
            })
    });
 }

Intercept XHR

const oldXHROpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
    // do something with the request
    this.addEventListener('load', function() {
        // do something with the response
    });
}

browser file access

import { saveAs } from 'file-saver';

export default () => {
    const fileUpload = useRef<HTMLInputElement>(null);
    
    const exportQuestions = () => {
        const fileName = 'questions.json';
        const fileToSave = new Blob([JSON.stringify(questions, null, 4)], {
            type: 'application/json',
        });
        saveAs(fileToSave, fileName);
    }

    const importQuestions = () => {
        if (null !== fileUpload.current) {
            const file = fileUpload.current.files![0];
            if (file) {
                var reader = new FileReader();
                reader.readAsText(file, "UTF-8");
                reader.onload = (evt: ProgressEvent<FileReader>) => {
                    if (evt.target && typeof evt.target.result === "string") {
                        console.log(JSON.parse(evt.target.result));
                    }
                }
            }
        }
    }

    return (
        <input
            ref={fileUpload}
            type="file"
            id="file-upload"
            accept="application/json"
            className={classes.file}
            onChange={() => importQuestions()}
            style={{ display: 'none' }}
        />
    );
}

remote console.log

Access your console.log output remotely