Skip to content

Commit

Permalink
fix(Util): DO NOT process any non-string type value
Browse files Browse the repository at this point in the history
  • Loading branch information
Macrox committed Jan 27, 2019
1 parent eea4cfa commit 2a3280f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/util/string.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { warning } from './log';
import { typeOf } from './object';

/**
* 将字符串转化为驼峰式写法
* @param {String} str 例:-webkit-transition
Expand All @@ -16,6 +19,14 @@ export function camelcase (str) {
* @return {String} 例:-webkit-transition
*/
export function hyphenate (str) {
if (typeof str !== 'string') {
warning(
'[ hyphenate(str: string): string ] ' +
`Expected arguments[0] to be a string but get a ${typeOf(str)}.` +
'It will return an empty string without any processing.'
);
return '';
}
return str.replace(/([A-Z])/g, $0 => `-${$0.toLowerCase()}`);
}

Expand All @@ -26,6 +37,15 @@ export function hyphenate (str) {
* @return {String} 例:
*/
export function template (tpl, object = {}) {
if (typeof tpl !== 'string') {
warning(
'[ template(tpl: string, object: object): string ] ' +
`Expected arguments[0] to be a string but get a ${typeOf(tpl)}.` +
'It will return an empty string without any processing.'
);
return '';
}

return tpl.replace(/\{[a-z]*\}/g, (str) => {
const key = str.substring(1, str.length - 1);
return object[key] || '';
Expand Down
16 changes: 16 additions & 0 deletions test/util/string-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,27 @@ describe('src/string.js', function() {
assert(string.hyphenate('transitionDelay') === 'transition-delay');
});

it('string.hyphenate(str) should return empty string if arg[0] is not a string', function () {
assert(string.hyphenate() === '');
assert(string.hyphenate(null) === '');
assert(string.hyphenate([]) === '');
assert(string.hyphenate({}) === '');
assert(string.hyphenate(function() {}) === '');
})

it('camelcase can restore the result of hyphenate', function () {
assert(string.camelcase(string.hyphenate('WebkitTransition')) === 'WebkitTransition');
});

it('string.template(tpl, obj) should return correct string', function () {
assert(string.template('当前{current}, 共{total}页', { total: 3, current: 1}) === '当前1, 共3页');
});

it('string.template(tpl, obj) should return empty string if arg[0] is not a string', function () {
assert(string.template() === '');
assert(string.template(null) === '');
assert(string.template([]) === '');
assert(string.template({}) === '');
assert(string.template(function() {}) === '');
})
});

0 comments on commit 2a3280f

Please sign in to comment.