Skip to content

Commit

Permalink
Merge pull request #10 from majkel88/master
Browse files Browse the repository at this point in the history
get function name - IE support
  • Loading branch information
mprzodala authored Jan 29, 2018
2 parents b21c97e + 73d309b commit fc9ce7c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
getDefaultValueForType,
getDefaultValueFromOptions,
wrapToArray,
getFunctionName,
} from './helpers';
import OneOfTypes from './OneOfTypes';
import SchemaType from './SchemaType';
Expand Down Expand Up @@ -297,7 +298,7 @@ class Schema {
}

validateType(type, value, key, index) {
const { name: typeName } = type;
const typeName = getFunctionName(type);
this.registerTypeIfNotExists(type, typeName);

if (typeof this.typesValidators[typeName] === 'function') {
Expand Down
12 changes: 12 additions & 0 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,15 @@ export const getDefaultValueFromOptions = (options) => {
}
return firstOption;
};

export const getFunctionName = (type) => {
const { name: typeName } = type;
if (typeof type === 'function' && !typeName) {
const functionString = type.toString();
return functionString
.substr(0, functionString.indexOf('('))
.replace('function ', '')
.trim();
}
return typeName;
};
15 changes: 15 additions & 0 deletions src/helpers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
getFieldType,
getDefaultValueForType,
getDefaultValueFromOptions,
getFunctionName,
} from './helpers';

describe('helpers', () => {
Expand Down Expand Up @@ -82,4 +83,18 @@ describe('helpers', () => {
expect(getFieldType(fooField)).toBe(String);
expect(getFieldType(barField)).toBe(String);
});

it('should return function name', () => {
const barFunction = function bar() {};
const fooFunction = function foo() {};
Object.defineProperty(fooFunction, 'name', { value: undefined });
expect(getFunctionName(barFunction)).toBe('bar');
expect(getFunctionName(String)).toBe('String');
expect(getFunctionName(Number)).toBe('Number');
expect(getFunctionName(Object)).toBe('Object');
expect(getFunctionName(Array)).toBe('Array');
expect(getFunctionName(Boolean)).toBe('Boolean');
expect(getFunctionName(Date)).toBe('Date');
expect(getFunctionName(fooFunction)).toBe('foo');
});
});

0 comments on commit fc9ce7c

Please sign in to comment.