/ember-no-get-with-default

transforms getWithDefault using Ember get

Primary LanguageJavaScript

ember-no-get-with-default-codemod

A collection of codemod's for ember-no-get-with-default-codemod.

Usage

To run a specific codemod from this project, you would run the following:

npx ember-no-get-with-default-codemod <TRANSFORM NAME> path/of/files/ or/some**/*glob.js

# or

yarn global add ember-no-get-with-default-codemod
ember-no-get-with-default-codemod <TRANSFORM NAME> path/of/files/ or/some**/*glob.js

Transforms

Before

const test = obj.getWithDefault('key', 'default');
const test2 = obj.getWithDefault('key', 'default').includes('foo');

After

const test = get(obj, 'key') !== undefined ? get(obj, 'key') : 'default';
const test2 = (get(obj, 'key') !== undefined ? get(obj, 'key') : 'default').includes('foo');

Before nullish coalescing

const test = obj.getWithDefault('key', 'default');
const test2 = obj.getWithDefault('key', 'default').includes('blah');

const test3 = getWithDefault(this, 'key', 'default');
const test4 = getWithDefault(this, 'key', 'default').includes('blah');
const test5 = getWithDefault(obj, `foo.${key}`, []);

After

import { get } from '@ember/object';
const test = get(obj, 'key') ?? 'default';
const test2 = (get(obj, 'key') ?? 'default').includes('blah');

const test3 = get(this, 'key') ?? 'default';
const test4 = (get(this, 'key') ?? 'default').includes('blah');
const test5 = get(obj, `foo.${key}`) ?? [];

Before comment nullish coalescing

const test = obj.getWithDefault('key', 'default');
const test2 = obj.getWithDefault('key', 'default').includes('blah');

After

import { get } from '@ember/object';
//TODO rewrite with `get(obj, 'key') ?? 'default'` if result can be null
const test = get(obj, 'key') !== undefined ? get(obj, 'key') : 'default';
//TODO rewrite with `get(obj, 'key') ?? 'default'` if result can be null
const test2 = (get(obj, 'key') !== undefined ? get(obj, 'key') : 'default').includes('blah');

Contributing

Installation

  • clone the repo
  • change into the repo directory
  • yarn

Options

 # Add leading comments to encourage migration. This is suitable for codebase that has not adopted the syntax yet.
--comment-nullish-coalescing

 # Transform to include nullish coalescing operator
--nullish-coalescing

Running tests

  • yarn test

Update Documentation

  • yarn update-docs

Debugging

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

Limitation

  • Does not add import 'get' when it's missing
  • Add transform to nullish coalescing

References