Skip to content

Commit 91529fc

Browse files
authored
Merge pull request #206 from github/extract-dasherize
extract dasherize into shared function
2 parents 5fd841e + 88c5e61 commit 91529fc

File tree

4 files changed

+27
-7
lines changed

4 files changed

+27
-7
lines changed

src/attr.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {CustomElement} from './custom-element.js'
2+
import {dasherize} from './dasherize.js'
23
import {meta} from './core.js'
34

45
const attrKey = 'attr'
@@ -79,9 +80,7 @@ export function initializeAttrs(instance: HTMLElement, names?: Iterable<string>)
7980
}
8081
}
8182

82-
function attrToAttributeName(name: string): string {
83-
return `data-${name.replace(/([A-Z]($|[a-z]))/g, '-$1')}`.replace(/--/g, '-').toLowerCase()
84-
}
83+
const attrToAttributeName = (name: string) => `data-${dasherize(name)}`
8584

8685
export function defineObservedAttributes(classObject: CustomElement): void {
8786
let observed = classObject.observedAttributes || []

src/dasherize.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const dasherize = (str: unknown): string =>
2+
String(str)
3+
.replace(/([A-Z]($|[a-z]))/g, '-$1')
4+
.replace(/--/g, '-')
5+
.replace(/^-|-$/, '')
6+
.toLowerCase()

src/register.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {CustomElement} from './custom-element.js'
2+
import {dasherize} from './dasherize.js'
23

34
/**
45
* Register the controller as a custom element.
@@ -8,10 +9,7 @@ import type {CustomElement} from './custom-element.js'
89
* Example: HelloController => hello-controller
910
*/
1011
export function register(classObject: CustomElement): void {
11-
const name = classObject.name
12-
.replace(/([A-Z]($|[a-z]))/g, '-$1')
13-
.replace(/(^-|-Element$)/g, '')
14-
.toLowerCase()
12+
const name = dasherize(classObject.name).replace(/-element$/, '')
1513
if (!window.customElements.get(name)) {
1614
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
1715
// @ts-ignore

test/dasherize.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import {expect} from '@open-wc/testing'
2+
import {dasherize} from '../src/dasherize.js'
3+
4+
describe('dasherize', () => {
5+
const tests = [
6+
['json', 'json'],
7+
['fooBar', 'foo-bar'],
8+
['FooBar', 'foo-bar'],
9+
['autofocusWhenReady', 'autofocus-when-ready'],
10+
['URLBar', 'url-bar'],
11+
['ClipX', 'clip-x']
12+
]
13+
14+
tests.map(([input, output]) =>
15+
it(`transforms ${input} to ${output}`, () => expect(dasherize(input)).to.equal(output))
16+
)
17+
})

0 commit comments

Comments
 (0)