Skip to content

Commit

Permalink
feat(prettier-plugin-jsdoc): add function to format objects
Browse files Browse the repository at this point in the history
  • Loading branch information
homer0 committed Oct 5, 2020
1 parent c111d54 commit c6a5d3b
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/fns/formatObjects.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const R = require('ramda');
const { isMatch, replaceDotOnTypeGeneric } = require('./utils');
/**
* @typedef {import('../types').PJPTypesOptions} PJPTypesOptions
*/

/**
* This is the function that actuall processes the types and the options of {@link formatObjects}.
* The reason this is on a separated function is to avoid adding composition inside the `when`.
*
* @callback ProcessTypeFn
* @param {string} type The type to format.
* @param {PJPTypesOptions} options The customization options.
* @returns {string}
*/

/**
* @type {ProcessTypeFn}
*/
const processType = R.curry((options, type) => R.when(
R.always(options.jsdocFormatDotForArraysAndObjects),
replaceDotOnTypeGeneric('Object', options.jsdocUseDotForArraysAndObjects),
)(type));

/**
* Formats array types depending on the customization options. If the type doesn't contain an
* array, it will be returned without modifications.
*
* @param {string} type The type to format.
* @param {PJPTypesOptions} options The customization options.
* @returns {string}
*/
const formatObjects = (type, options) => R.when(
isMatch(/Object\s*\.?\s*</),
processType(options),
)(type);

module.exports.formatObjects = formatObjects;
34 changes: 34 additions & 0 deletions test/fns/formatObject.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
jest.unmock('../../src/fns/formatObjects');
jest.unmock('../../src/fns/utils');

const { formatObjects } = require('../../src/fns/formatObjects');

describe('formatObjects', () => {
it('should add a dot before objects\' generics', () => {
// Given
const input = 'Object<string,Object.<string,Object<string,number>>>';
const output = 'Object.<string,Object.<string,Object.<string,number>>>';
let result = null;
// When
result = formatObjects(input, {
jsdocFormatDotForArraysAndObjects: true,
jsdocUseDotForArraysAndObjects: true,
});
// Then
expect(result).toBe(output);
});

it('should remove the dot before objcects\' generics', () => {
// Given
const input = 'Object.<string,Object<string,Object.<string,number>>>';
const output = 'Object<string,Object<string,Object<string,number>>>';
let result = null;
// When
result = formatObjects(input, {
jsdocFormatDotForArraysAndObjects: true,
jsdocUseDotForArraysAndObjects: false,
});
// Then
expect(result).toBe(output);
});
});

0 comments on commit c6a5d3b

Please sign in to comment.