r101718 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r101717‎ | r101718 | r101719 >
Date:22:00, 2 November 2011
Author:tparscal
Status:ok
Tags:
Comment:
Copying serializer code to VisualEditor extension
Modified paths:
  • /trunk/extensions/VisualEditor/modules/es/es.JsonSerializer.js (added) (history)

Diff [purge]

Index: trunk/extensions/VisualEditor/modules/es/es.JsonSerializer.js
@@ -0,0 +1,100 @@
 2+/**
 3+ * Serializes a WikiDom into JSON.
 4+ *
 5+ * @class
 6+ * @constructor
 7+ * @extends {es.Serializer}
 8+ * @property options {Object} List of options for serialization
 9+ * @property options.indentWith {String} Text to use as indentation, such as \t or 4 spaces
 10+ */
 11+es.JsonSerializer = function( options ) {
 12+ es.Serializer.call( this );
 13+ this.options = $.extend( {
 14+ 'indentWith': '\t'
 15+ }, options || {} );
 16+};
 17+
 18+/* Static Methods */
 19+
 20+es.JsonSerializer.typeOf = function( value ) {
 21+ if ( typeof value === 'object' ) {
 22+ if ( value === null ) {
 23+ return 'null';
 24+ }
 25+ switch ( value.constructor ) {
 26+ case [].constructor:
 27+ return 'array';
 28+ case ( new Date() ).constructor:
 29+ return 'date';
 30+ case ( new RegExp() ).constructor:
 31+ return 'regex';
 32+ default:
 33+ return 'object';
 34+ }
 35+ }
 36+ return typeof value;
 37+};
 38+
 39+es.JsonSerializer.prototype.encode = function( data, indention ) {
 40+ if ( indention === undefined ) {
 41+ indention = '';
 42+ }
 43+ var type = es.JsonSerializer.typeOf( data ),
 44+ key;
 45+
 46+ // Open object/array
 47+ var json = '';
 48+ if ( type === 'array' ) {
 49+ if (data.length === 0) {
 50+ // Empty array
 51+ return '[]';
 52+ }
 53+ json += '[';
 54+ } else {
 55+ var empty = true;
 56+ for ( key in data ) {
 57+ if ( data.hasOwnProperty( key ) ) {
 58+ empty = false;
 59+ break;
 60+ }
 61+ }
 62+ if ( empty ) {
 63+ return '{}';
 64+ }
 65+ json += '{';
 66+ }
 67+
 68+ // Iterate over items
 69+ var comma = false;
 70+ for ( key in data ) {
 71+ if ( data.hasOwnProperty( key ) ) {
 72+ json += ( comma ? ',' : '' ) + '\n' + indention + this.options.indentWith +
 73+ ( type === 'array' ? '' : '"' + key + '"' + ': ' );
 74+ switch ( es.JsonSerializer.typeOf( data[key] ) ) {
 75+ case 'array':
 76+ case 'object':
 77+ json += this.encode( data[key], indention + this.options.indentWith );
 78+ break;
 79+ case 'boolean':
 80+ case 'number':
 81+ json += data[key].toString();
 82+ break;
 83+ case 'null':
 84+ json += 'null';
 85+ break;
 86+ case 'string':
 87+ json += '"' + data[key]
 88+ .replace(/[\n]/g, '\\n')
 89+ .replace(/[\t]/g, '\\t') + '"';
 90+ break;
 91+ // Skip other types
 92+ }
 93+ comma = true;
 94+ }
 95+ }
 96+
 97+ // Close object/array
 98+ json += '\n' + indention + ( type === 'array' ? ']' : '}' );
 99+
 100+ return json;
 101+};

Status & tagging log