Skip to content

Instantly share code, notes, and snippets.

@anithri
Last active September 29, 2019 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anithri/b8d1639c498931948ccad8cad43519a3 to your computer and use it in GitHub Desktop.
Save anithri/b8d1639c498931948ccad8cad43519a3 to your computer and use it in GitHub Desktop.
nameMaker.js utililty
// nameMaker.js
const cc = require('change-case')
const inflection = require('inflection')
const suffixer = {
get: function(target, prop, _receiver) {
if (target.hasOwnProperty(prop)) return target[prop]
if (prop[0] === prop[0].toLowerCase()) {
return `${target.name}${cc.pascal(prop)}`
} else if (prop === prop.toUpperCase()) {
return `${target.NAME}_${prop}`
} else {
return `${target.Name}${cc.pascal(prop)}`
}
},
}
const nameMaker = ({ name, ...args }) => {
const baseData = {
name: inflection.singularize(cc.camel(name)),
Name: inflection.singularize(cc.pascal(name)),
names: inflection.pluralize(cc.camel(name)),
Names: inflection.pluralize(cc.pascal(name)),
NAME: cc.constant(inflection.singularize(cc.pascal(name))),
NAMES: cc.constant(inflection.pluralize(cc.camel(name))),
}
Object.assign(args, baseData)
return new Proxy(baseData, suffixer)
}
module.exports = { nameMaker }
// nameMaker.test.js
import { nameMaker } from '../nameMaker'
describe("nameMaker({name: 'wooticusPrime'})", function() {
it('should be a function', () => {
expect(nameMaker).toBeFunction()
})
it('should return an object with 6 properties', function() {
const result = nameMaker({ name: 'wooticusPrime' })
expect(result).toBeObject()
expect(result.name).toBe('wooticusPrime')
expect(result.Name).toBe('WooticusPrime')
expect(result.names).toBe('wooticusPrimes')
expect(result.Names).toBe('WooticusPrimes')
expect(result.NAME).toBe('WOOTICUS_PRIME')
expect(result.NAMES).toBe('WOOTICUS_PRIMES')
})
describe('new Proxy(nameMaker({wooticusPrime}, suffixer)', () => {
it('should return a name matching prop used', () => {
const result = nameMaker({ name: 'wooticusPrime' })
expect(result.shape).toBe('wooticusPrimeShape')
expect(result.Shape).toBe('WooticusPrimeShape')
expect(result.SHAPE).toBe('WOOTICUS_PRIME_SHAPE')
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment