Deferred Promise

Found myself in a situation where I wanted to execute a process and then check back on it later to be sure it had completed.

class MyClass {
  constructor() {
    this.readyPromise = new Promise(
      resolve => (this.readyResolve = resolve)
    );
  }

  async executeProcesses() {
    await // ...executing processes...
    this.readyResolve();
  }

  ready() { return this.readyPromise }
}
Continue reading “Deferred Promise”

Chrome extension MV2 access to page data

Chrome extensions exist in an “isolated world” to prevent global var collisions between the website and the extension that runs on a given website. This mostly applies to content_scripts in an extension.

E.g. window.foo: my extension declares foo in the global scope and the website the extension runs on also declares foo in the global scope. With “isolated world” scoping for the extension, this is not a worry since it doesn’t share scope with the web page it runs on.

Continue reading “Chrome extension MV2 access to page data”

Colored Console Output

const out = {

  end: '\x1b[0m',

  // Modifiers.
  blink: '\x1b[5m',
  bright: '\x1b[1m',
  dim: '\x1b[2m',
  hidden: '\x1b[8m',
  reverse: '\x1b[7m',
  underscore: '\x1b[4m',

  // Foreground Colors.
  black: '\x1b[30m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
  green: '\x1b[32m',
  magenta: '\x1b[35m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  white: '\x1b[37m',

  // Background Colors.
  bgBlack: '\x1b[40m',
  bgBlue: '\x1b[44m',
  bgCyan: '\x1b[46m',
  bgGreen: '\x1b[42m',
  bgMagenta: '\x1b[45m',
  bgRed: '\x1b[41m',
  bgYellow: '\x1b[43m',
  bgWhite: '\x1b[47m',
};

Usage:

console.log(out.red, 'Something went wrong:', err, out.end);

Validate the Crickets’ Nest

I have a problem getting values from deeply nested objects: if one of the properties along the namespace is incorrect|modified|removed, Javascript throws. To avoid this, you can end up with obnoxious validation:

// Trying to get this.data.homeScene.user.name
const isValid = (
  typeof this.data === 'object' &&
  typeof this.data.homeScene === 'object' &&
  typeof this.data.homeScene.user === 'object' &&
  typeof this.data.homeScene.user.name === 'string'
);
if (isValid) {
  const { name } = this.data.homeScene.user;
  ...
}

What if I made a reusable helper to validate the namespace and return the value?

export default function getNamespace(startObj, path) {
  const isValidArgs = (
    typeof startObj === 'object' &&
    typeof path === 'string'
  );
  if (!isValidArgs) return undefined;

  const finalValue = path
    .split('.')
    .reduce((obj, p) => ((typeof obj === 'object') 
      ? obj[p]
      : undefined
    ), startObj);{

  return finalValue;
}

Now the obnoxious validation looks like this:

// Trying to get this.data.homeScene.user.name
const name = getNamespace(this, 'data.homeScene.user.name');
if (name) { ... }

Dude! Sweet!