@davidosborn/crypto-tax-calculator
Version:
A tool to calculate the capital gains of cryptocurrency assets for Canadian taxes
60 lines (47 loc) • 1.58 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var _stream = _interopRequireDefault(require("stream"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* A stream that normalizes the delimiters of a CSV file.
*/
class CsvNormalizeStream extends _stream.default.Transform {
/**
* Initializes a new instance.
*/
constructor() {
super();
this._delimiter = null;
}
/**
* Normalizes the delimiters of a CSV file.
* @param {buffer|string} chunk The CSV file.
* @param {string} encoding The encoding type.
* @param {function} callback A callback for when the transformation is complete.
*/
async _transform(chunk, encoding, callback) {
let line = chunk.toString().trim(); // Determine the delimiter from the header.
if (this._delimiter == null) this._delimiter = line.split('\t').length > line.split(',').length ? '\t' : ',';
if (this._delimiter !== ',') {
// It should be safe to drop the existing commas.
line = line.replace(/,/g, ''); // Replace the delimiter with a comma.
if (this._delimiter === '\t') line = line.replace(/\t/g, ',');else {
let i = -1;
while (true) {
line = line.replace(this._delimiter, ',');
let j = line.lastIndexOf(',');
if (j === i) break;
i = j;
}
}
}
this.push(line + '\n');
callback();
}
}
function _default(...args) {
return new CsvNormalizeStream(...args);
}