Skip to content

Commit 9c8d6ea

Browse files
committed
增加and解析器组合子
1 parent f4a15c6 commit 9c8d6ea

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "jcon",
33
"description": "A JavaScript parser combinator Library",
4-
"version": "0.3.1",
4+
"version": "0.3.2",
55
"homepage": "https://github.com/takumi4ichi",
66
"author": {
77
"name": "takumi4ichi",

src/jcon.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,21 @@ var jcon = (function(undefined){
176176
return jcon.not.apply(jcon, args);
177177
},
178178

179+
/**
180+
* @method and
181+
*
182+
* @param {Parser} parser 原解析器
183+
*
184+
* @desc 组合n个解析器,依次尝试解析,全部成功则解析成功,解析结果为被组合的解析器的最短解析结果
185+
186+
*
187+
*/
188+
and: function(){
189+
var args = slice.call(arguments, 0);
190+
args.unshift(this);
191+
return jcon.and.apply(jcon, args);
192+
},
193+
179194

180195
/**
181196
* @method or
@@ -484,6 +499,36 @@ var jcon = (function(undefined){
484499
},
485500

486501

502+
503+
/**
504+
* @method and
505+
*
506+
* @param {Array:Parser} arguments 组合n个解析器,依次尝试解析,全部成功则解析成功,解析结果为被组合的解析器的最短解析结果
507+
*
508+
* @desc 进行解析器的与组合
509+
*/
510+
and: function(){
511+
var args = slice.call(arguments, 0);
512+
return Parser(function(stream, index){
513+
var parser,
514+
result,
515+
results = [],
516+
parserIndex = 0;
517+
while(parser = args[parserIndex++]){
518+
result = parser.parse(stream, index);
519+
if(result.success){
520+
results.push(result);
521+
}
522+
}
523+
if(results.length === args.length){
524+
results.sort(function(a, b){return a.endIndex - b.endIndex;});
525+
return results[0];
526+
}else{
527+
return fail(index, 'in and_parser');
528+
}
529+
});
530+
},
531+
487532
/**
488533
* @method or
489534
*

test/parser_test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ module.exports = (function(){
3333
test.done();
3434
},
3535

36+
and: function(test){
37+
test.equal(jcon.and(jcon.string('111'), jcon.regex(/\d+/)).parse('1111').value, '111', 'and');
38+
test.equal(jcon.and(jcon.string('111'), jcon.regex(/\d/)).parse('1111').value, '1', 'and');
39+
test.equal(jcon.and(jcon.string('111'), jcon.not(jcon.regex(/[a-z]/)).many()).parse('1111').value, '111', 'and');
40+
test.done();
41+
},
3642
or: function(test){
3743

3844

0 commit comments

Comments
 (0)