paskvilwiki

up: programming

JS

last updated 2020-12

simple mapping

let a = {a: 1, b: 2, c: 3};

Object.keys(a).map(i => console.log(i));
> a
> b
> c
>> [undefined, undefined, undefined]

a = [1, 2, 3];
a.map((i, k) => console.log(i, k));
> 1 0
> 2 1
> 3 2
>> [undefined, undefined, undefined]

// fill() is required here, as it materializes the Array;
// otherwise, Array(8) would be treated as empty array by map()
Array(8).fill().map((_, i) => i * i);
>> [0, 1, 4, 9, 16, 25, 36, 49]

fetch patterns

fetch("url", { /* options */ })
  .then((response) => {
    if (!response.ok)
      throw new Error('Network response was not ok');
    return response.json();  // or response.blob(), etc.
  })
  .then((data) => {
    // do something with the data received
  })
  .catch((error) => {
    console.error('Failed to fetch:', error);
  });

environment variables in webpack

webpack does not have access to the environment (duh), so you need to "bake" any relevant environment variables into webpack during the build:

new webpack.DefinePlugin({
  'process.env': {
    NODE_ENV: JSON.stringify(process.env.NODE_ENV),
    STAGE: JSON.stringify(process.env.STAGE),
    // ...
  }
})

debugging in VS Code on Linux

  • no extension needed - VS Code's built-in JavaScript debugger runs chrome launch configs (the old Debugger for Chrome extension is deprecated)
  • open the launch.json file, and edit as follows:
    • a custom profile - user-data-dir - is used, to make sure you have a clean (enough) slate
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "runtimeExecutable": "/usr/bin/chromium-browser",
      "runtimeArgs": ["--remote-debugging-port=9222", "--user-data-dir=/home/user/tmp/remote-profile"],
      "name": "Launch Chrome against localhost",
      "url": "http://localhost:3000",
      "webRoot": "${workspaceFolder}"
    }
  ]
}
  • run the npm (the port used should correspond to the url key above)
  • hit debug in VS Code, add breakpoints, etc., and enjoy!
    • this will actually open a new browser window, as a subwindow of VS Code, neat!