Created
October 14, 2016 08:56
-
-
Save henrahmagix/314f03e6bc88c55e3d7260d4c4b9969a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function invert(initial) { | |
return Object.keys(initial) | |
.reduce((obj, key) => { | |
obj[initial[key]] = key; | |
return obj; | |
}, {}); | |
} | |
const SELECTOR_FIRST_CHARS = { | |
ID: '#', | |
CLASS: '.', | |
ATTRIBUTE: '[' | |
}; | |
const SELECTOR_TYPES = invert(SELECTOR_FIRST_CHARS); | |
const R_SELECTOR = /^[.#[]/; | |
class SelectorError extends Error { | |
constructor(message) { | |
super(message); | |
this.name = 'SelectorError'; | |
} | |
} | |
class Selector extends String { | |
constructor(string) { | |
if (!string.match(R_SELECTOR)) { | |
throw new SelectorError('Value must be a CSS selector'); | |
} | |
super(string); | |
this.type = SELECTOR_TYPES[string.charAt(0)]; | |
} | |
toRaw() { | |
let string = this.toString(); | |
if (this.type === 'ATTRIBUTE') { | |
return string; | |
} | |
return string.slice(1); | |
} | |
} | |
const idString = new Selector('#my-id'); | |
const classString = new Selector('.my-class'); | |
const attributeString = new Selector('[foo="bar"]'); | |
console.log(idString.toString()); // #my-id | |
console.log(idString.toRaw()); // my-id | |
console.log(idString.type); // ID | |
console.log(classString.toString()); // .my-class | |
console.log(classString.toRaw()); // my-class | |
console.log(classString.type); // CLASS | |
console.log(attributeString.toString()); // [foo="bar"] | |
console.log(attributeString.toRaw()); // [foo="bar"] | |
console.log(attributeString.type); // ATTRIBUTE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment