Created
July 19, 2013 18:17
-
-
Save Leko/6041229 to your computer and use it in GitHub Desktop.
parse inputs method in JavaScript
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
/** | |
* 標準入力のパースと汎用関数を提供する | |
* @method parseInput | |
* @param {Boolean} [useSplitSpace] スペースを区切り文字として利用する | |
* @default true | |
*/ | |
function parseInput(useSplitSpace) { | |
var index = 0, | |
ret = [], | |
input = require("fs").readFileSync("/dev/stdin", "utf8"), | |
inputs = input.replace(/\r/g, '').split("\n"); | |
useSplitSpace = useSplitSpace || true; | |
// 入力を改行/空白で区切り平坦な配列に変換 | |
inputs.forEach(function(val) { | |
if ( useSplitSpace && val !== "" ) { | |
val.split(" ").forEach(function(el) { | |
if ( el !== "" ) ret.push(el); | |
}); | |
} else { | |
ret.push(val); | |
} | |
}); | |
return { | |
/** | |
* 次の要素があるかを調べる | |
* valが与えられた場合、次の要素がvalかどうかを調べる | |
* @method hasNext | |
* @param {All} 任意の値 | |
* @return {Boolean} 次の要素があればtrue、無ければfalse | |
* valがある場合、次の要素がvalならtrue、valでなければfalse | |
*/ | |
hasNext: function(val) { | |
if ( typeof val === "undefined" ) { | |
return typeof ret[index] !== "undefined"; | |
} else { | |
return ret[index] === val; | |
} | |
}, | |
/** | |
* 現在の添字の次の要素を取得し、添字を1進める | |
* 取得できる要素が無い場合、RangeErrorを投げる | |
* @method next | |
* @return {String} 次の添字に格納されている要素 | |
*/ | |
next: function() { | |
if ( typeof ret[index+1] === "undefined" ) throw new RangeError("Index out of bounds at '" + index+1 + "'"); | |
return ret[index++]; | |
}, | |
/** | |
* 現在の添字の次の要素を数値として取得し、添字を1進める | |
* 取得できる要素が無い場合、RangeErrorを投げる | |
* 取得した要素が数値出ない場合、TypeErrorを投げる | |
* @method nextNumber | |
* @return {Number} 数値に変換した要素 | |
*/ | |
nextNumber: function () { | |
if ( !/^\d$/.test(this.top()) ) throw new TypeError("'" + this.top() + "' cannot convet to Number"); | |
return +this.next(); | |
}, | |
/** | |
* 現在の添字の次の要素を整数値として取得し、添字を1進める | |
* 取得できる要素が無い場合、RangeErrorを投げる | |
* 取得した要素が数値出ない場合、TypeErrorを投げる | |
* @method nextInt | |
* @return {Number} 整数値に変換した要素 | |
*/ | |
nextInt: function() { | |
return parseInt(this.nextNumber()); | |
}, | |
/** | |
* 現在の添字の要素を返す。呼び出されても添字を変化させない | |
* @method top | |
* @return {String} 現在の添字の要素 | |
*/ | |
top: function() { | |
return ret[index]; | |
}, | |
/** | |
* 添字を0に戻す | |
* @method rewind | |
* @return なし | |
*/ | |
rewind: function() { | |
index = 0; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment