Created
January 11, 2012 16:17
-
-
Save think49/1595411 to your computer and use it in GitHub Desktop.
parse-object-literal.js : ES5 規定のオブジェクト初期化子構文(ObjectLiteral)をパースしてオブジェクトを返す関数。ただし、この機能は簡易的で ES5 規定に部分的に準拠しています。
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
/** | |
* parse-object-literal.js | |
* parseObjectLiteral function returns an object, by parsing "ObjectLiteral". | |
* However, this function is simple. It isn't based upon the part of ES5. | |
* | |
* @version 1.0.1b | |
* @author think49 | |
* @url https://gist.github.com/1595411 | |
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License) | |
* @see <a href="http://es5.github.com/#x11.1.5">11.1.5 Object Initialiser - Annotated ES5</a> | |
*/ | |
'use strict'; | |
var parseObjectLiteral = (function () { | |
var trim = (function () { | |
if (typeof String.prototype.trim === 'function') { | |
return function (string) { | |
return string.trim(); | |
}; | |
} | |
return function (string) { | |
return string.replace(/^\s+|\s+$/g, ''); | |
}; | |
}()); | |
function parseStringLiteral (string) { | |
if (string.indexOf('\x22') === 0 && string.lastIndexOf('\x22') === string.length - 1 || string.indexOf('\x27') === 0 && string.lastIndexOf('\x27') === string.length - 1) { | |
string = string.slice(1, -1).replace(/\x5C([\s\S])/g, '$1'); | |
} | |
return string; | |
} | |
function parseObjectLiteral (string) { | |
var object, array; | |
string = trim(String(string)); | |
if (string.indexOf('{') !== 0 || string.lastIndexOf('}') !== string.length - 1) { | |
throw new SyntaxError; | |
} | |
string = trim(string.slice(1, -1)); | |
array = string.split(','); | |
object = {}; | |
for (var i = 0, l = array.length, data, index; i < l; ++i) { | |
data = array[i]; | |
index = data.indexOf(':'); | |
object[parseStringLiteral(trim(data.slice(0, index)))] = parseStringLiteral(trim(data.slice(index + 1))); | |
} | |
return object; | |
} | |
return parseObjectLiteral; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
コードを簡略化した為、現版には次の制約があります。(いずれもエラー出力せずに不正なオブジェクトが返されます)