Skip to content

Instantly share code, notes, and snippets.

@think49
Created January 11, 2012 16:17
Show Gist options
  • Save think49/1595411 to your computer and use it in GitHub Desktop.
Save think49/1595411 to your computer and use it in GitHub Desktop.
parse-object-literal.js : ES5 規定のオブジェクト初期化子構文(ObjectLiteral)をパースしてオブジェクトを返す関数。ただし、この機能は簡易的で ES5 規定に部分的に準拠しています。
/**
* 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;
}());
@think49
Copy link
Author

think49 commented Jan 11, 2012

コードを簡略化した為、現版には次の制約があります。(いずれもエラー出力せずに不正なオブジェクトが返されます)

  • プロパティ名に ":" を含めることが出来ません。
  • 文字列リテラルでバックスラッシュエスケープ以外のエスケープシーケンスをサポートしません。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment