Skip to content

Instantly share code, notes, and snippets.

@zaverden
Created June 1, 2018 12:01
Show Gist options
  • Save zaverden/07d8d825c95cfb99a46f0f982e2c7ecc to your computer and use it in GitHub Desktop.
Save zaverden/07d8d825c95cfb99a46f0f982e2c7ecc to your computer and use it in GitHub Desktop.
const moo = require('moo');
const Time = require('./time');
const parser = moo.compile({
VAR: {
match: /{[a-zA-Z_]\w*}/,
keywords: { PREDEF: ['{today}'] } // predefined keywords
},
OP: ['and', 'or', '+', 'at'],
DAY: {
match: /\d+d/, // 5d 12d
value: s => parseInt(s) // it automatically cut off non digit symbols
},
HOUR: {
match: /\d+h/, // 1h 433h
value: s => parseInt(s) // it automatically cut off non digit symbols
},
TIME: [
{
match: 'noon', value: () => new Time(12, 0)
}, {
match: 'midnight', value: () => new Time(0, 0)
}, {
match: /(?:[0-9]|0[0-9]|1[0-9]|2[0-3])(?::[0-5][0-9])?[ap]m/, // 12am 3:45pm
value: Time.parse12format
}, {
match: /(?:[0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]/, // 23:59 3:45
value: Time.parse24format
}
],
STR: [
/".*?"/, // double-quoted
/'.*?'/ // single-quoted
],
WS: { match: /\s+/, lineBreaks: true }
});
const str = `
"hello \'ere"
{today}
{my_var}
12h
3d
12am
12pm
5am
3:09pm
23:59`;
console.log('input: ', str, '\n\nparsed:');
for (const { type, value, text } of parser.reset(str)) {
if (type !== 'WS') {
console.log(type, `${value}`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment