Last active
August 29, 2015 14:03
-
-
Save jpiccari/ce546178887a02194f40 to your computer and use it in GitHub Desktop.
Quick demo of how a JavaScript based selector engine might work.
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 select(selector) { | |
var elements = [document], | |
queryStart = 0, | |
callQueue = [], | |
temp, | |
i; | |
for (i = 0; i < selector.length; i++) { | |
switch (selector[i]) { | |
case '#': | |
queryStart = i + 1; | |
method = 'getElementById'; | |
break; | |
case '.': | |
queryStart = i + 1; | |
method = 'getElementsByClassName'; | |
break; | |
case ' ': | |
callQueue.push({ | |
method: method, | |
argument: selector.substring(queryStart, i) | |
}); | |
queryStart = i + 1; | |
break; | |
} | |
} | |
callQueue.push({ | |
method: method, | |
argument: selector.substring(queryStart, i) | |
}); | |
while (callQueue.length) { | |
temp = callQueue.shift(); | |
for (i = elements.length - 1; i >= 0; i--) { | |
temp = elements.shift()[temp.method](temp.argument); | |
elements.push.apply(elements, temp instanceof HTMLCollection ? temp : [temp]); | |
} | |
} | |
return elements; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment