Skip to content

Instantly share code, notes, and snippets.

@ryugoo
Forked from tomotaka/ltsv.dart
Last active December 12, 2015 07:29
Show Gist options
  • Save ryugoo/4737235 to your computer and use it in GitHub Desktop.
Save ryugoo/4737235 to your computer and use it in GitHub Desktop.
/*jslint devel:true */
/*global window, exports */
(function (root) {
"use strict";
// Prototype extension
if (!Array.prototype.removeAt) {
Array.prototype.removeAt = function (idx) {
if (typeof idx !== "number") {
throw new TypeError("removeAt argument is required Integer");
}
var el = this[idx];
if (el) {
this.splice(idx, 1);
}
return el;
};
}
if (!Object.keys) {
Object.keys = function (obj) {
if ((typeof obj !== "object" && typeof obj !== "function") || obj === null) {
throw new TypeError("Object.keys called on a non-object");
}
var key, keys = [];
for (key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
}
/**
* Parse LTSV
* @param {String} str LTSV format string
* @return {Object} Parsed object
*/
function parseLTSV(str) {
// Variables
var ret, kva, kvi, i, l, chunks, name;
// Initialize
ret = {};
kva = str.replace(/(^[\s ]+)|([\s ]+$)/g, "").split("\t");
// Convert
for (i = 0, l = kva.length; i < l; i += 1) {
kvi = kva[i];
chunks = kvi.split(":");
name = chunks.removeAt(0);
ret[name] = chunks.join(":");
}
return ret;
}
/**
* Dump LTSV
* @param {Object} obj Dump object
* @return {String} Dumped string
*/
function dumpLTSV(obj) {
// Variables
var keys, i, l, result, label;
// Initialize
keys = Object.keys(obj);
// Mapping
for (i = 0, l = keys.length, result = []; i < l; i += 1) {
label = keys[i];
result.push(label + ":" + obj[label]);
}
return result.join("\t");
}
if (typeof exports !== "undefined") {
exports.LTSV = {
parse: parseLTSV,
dump: dumpLTSV
};
} else {
root.LTSV = {
parse: parseLTSV,
dump: dumpLTSV
};
}
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment