Created
April 8, 2016 09:23
-
-
Save icecreamliker/bc132255c281f72057a5952557dba77d to your computer and use it in GitHub Desktop.
simple less tokenizer
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
| var fs = require('fs'); | |
| function tokenizer(file) { | |
| var content = fs.readFileSync(file, { | |
| encoding: 'utf-8' | |
| }); | |
| this.lines = content.split('\n'); | |
| } | |
| tokenizer.prototype = { | |
| parse: function() { | |
| return this.truncate().removeSpaceLines().split(); | |
| }, | |
| truncate: function() { | |
| // 0: normal pattern | |
| // 1: /* | |
| var flag = 0, | |
| i = 0; // index of the line | |
| this.lines = this.lines.map(function(line) { | |
| switch (flag) { | |
| case 0: | |
| if ((i = line.indexOf('//')) !== -1) { | |
| return line.slice(0, i); | |
| } else if ((i = line.indexOf('/*')) !== -1) { | |
| flag = 1; | |
| return line.slice(0, i); | |
| } else { | |
| return line; | |
| } | |
| case 1: | |
| if ((i = line.indexOf('*/')) !== -1) { | |
| flag = 0; | |
| return line.slice(i + 2); | |
| } else { | |
| return ''; | |
| } | |
| break; | |
| default: | |
| break; | |
| } | |
| }); | |
| return this; | |
| }, | |
| removeSpaceLines: function() { | |
| this.lines = this.lines.filter(function(line) { | |
| if (line.trim() === '') { | |
| return false; | |
| } | |
| return true; | |
| }); | |
| return this; | |
| }, | |
| split: function() { | |
| var stack = [], | |
| tuple = null; | |
| // @type: KEY, VALUE | |
| this.lines.forEach(function(line) { | |
| tuple = line.split(':'); | |
| stack.push({ | |
| type: 'KEY', | |
| value: tuple[0].slice(1) | |
| }, { | |
| type: 'VALUE', | |
| value: tuple[1].split(';')[0].trim() | |
| }); | |
| }); | |
| return stack; | |
| } | |
| }; | |
| module.exports = tokenizer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment