Skip to content

Instantly share code, notes, and snippets.

@mdamien
Created February 11, 2016 18:44
Show Gist options
  • Save mdamien/bffe66cfc3d4b6e68501 to your computer and use it in GitHub Desktop.
Save mdamien/bffe66cfc3d4b6e68501 to your computer and use it in GitHub Desktop.
arr2tsv.js simple TSV writer
// Small utility function to export an array to tsv
// Inspired by https://github.com/uselesscode/ucsv/blob/master/source/core.js
define(['underscore'], function (_) {
var separator = '\t';
var rxIsInt = /^\d+$/;
var rxIsFloat = /^\d*\.\d+$|^\d+\.\d*$/;
// If a string has leading or trailing space,
// contains the separator, double quote or a newline
// it needs to be quoted
var rxNeedsQuoting = new RegExp('^\s|\s$|' + separator + '|"|\n');
var prepField = function (field) {
if (_.isString(field)) {
// Escape any " with double " ("")
field = field.replace(/"/g, '""');
// If the field starts or ends with whitespace, contains " or , or a newline or
// is a string representing a number, quote it.
if (rxNeedsQuoting.test(field) || rxIsInt.test(field) || rxIsFloat.test(field)) {
field = '"' + field + '"';
// quote empty strings
} else if (field === "") {
field = '""';
}
} else if (_.isNumber(field)) {
field = field.toString(10);
} else if (field === null || field === undefined) {
field = '';
} else {
field = field.toString();
}
return field;
};
/**
Converts an array into a Tabulation Separated Values string.
Each item in the array should be an array that represents one row in the CSV.
Nulls and undefined values are interpreted as empty fields.
@method arr2tsv
@param {String} a The array to convert
@returns {String} A TSV representation of the provided array.
@example
var books = [
['JavaScript: The Good Parts', 'Crockford, Douglas', 2008],
['Object-Oriented JavaScript', 'Stefanov, Stoyan', 2008],
['Effective JavaScript', 'Herman, David', 2012]
];
var tsv = arr2tsv(books);
// tsv now contains:
//
// JavaScript: The Good Parts Crockford, Douglas 2008\n
// Object-Oriented JavaScript Stefanov, Stoyan 2008\n
// Effective JavaScript Herman, David 2012\n
*/
var arr2tsv = function(a) {
var out = '';
for (var i = 0; i < a.length; i += 1) {
var row = a[i];
for (var j = 0; j < row.length; j += 1) {
var cur = row[j];
cur = prepField(cur);
out += j < row.length - 1 ? cur + separator : cur;
}
out += "\n";
}
return out;
};
return arr2tsv;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment