Browse Source

feat: add jsonNetCamelCase as case util

pull/6405/head
Arman Ozak 6 years ago
parent
commit
4f7167595e
  1. 37
      npm/ng-packs/packages/theme-shared/extensions/src/lib/utils/case.util.ts
  2. 18
      npm/ng-packs/packages/theme-shared/extensions/src/tests/case.util.spec.ts

37
npm/ng-packs/packages/theme-shared/extensions/src/lib/utils/case.util.ts

@ -0,0 +1,37 @@
// https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Utilities/StringUtils.cs#L155
export function jsonNetCamelCase(str: string) {
if (!str || !isUpperCase(str[0])) return str;
const chars = str.split('');
const { length } = chars;
for (let i = 0; i < length; i++) {
if (i === 1 && !isUpperCase(chars[i])) break;
const hasNext = i + 1 < length;
if (i > 0 && hasNext && !isUpperCase(chars[i + 1])) {
if (isSeparator(chars[i + 1])) {
chars[i] = toLowerCase(chars[i]);
}
break;
}
chars[i] = toLowerCase(chars[i]);
}
return chars.join('');
}
function isSeparator(str = '') {
return /[\s\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]+/.test(str);
}
function isUpperCase(str = '') {
return /[A-Z]+/.test(str);
}
function toLowerCase(str = '') {
return str.toLowerCase();
}

18
npm/ng-packs/packages/theme-shared/extensions/src/tests/case.util.spec.ts

@ -0,0 +1,18 @@
import { jsonNetCamelCase } from '../lib/utils/case.util';
describe('Case Utils', () => {
describe('#jsonNetCamelCase', () => {
test.each`
input | output
${'Primary'} | ${'primary'}
${'PrimaryRole'} | ${'primaryRole'}
${'Primary Role'} | ${'primary Role'}
${'PrimaryRole_Text'} | ${'primaryRole_Text'}
${'ISBN'} | ${'isbn'}
${''} | ${''}
${'iMDB'} | ${'iMDB'}
`('should return $output when input is $input', ({ input, output }) => {
expect(jsonNetCamelCase(input)).toBe(output);
});
});
});
Loading…
Cancel
Save