I'm working on a visualization in D3 and I'm still in the learning process (JS included) and I want to remove the duplicated code from maxExportYears
and maxImportYears
.
function calcMaximum(json) {
let maxExportYears = json.map(function (obj) {
let maxByYear = [];
obj.entries.map( function(entry) {
maxByYear.push(parseFloat(entry.exported));
});
return d3.max(maxByYear, function(d) { return d; });
});
/// calculate the maximum Export across all years
let maxExport = d3.max(maxExportYears, function(d) {return d;} );
/// calculate the maximum Import on each year
let maxImportYears = json.map(function (obj) {
let maxByYear = [];
obj.entries.map( function(entry) {
maxByYear.push(parseFloat(entry.imported));
});
return d3.max(maxByYear, function(d) { return d; });
});
/// calculate the maximum Import across all years
let maxImport = d3.max(maxImportYears, function(d) {return d;} );
/// calculate the maximum between maxExport and maxImport
let maximum = d3.max([maxExport, maxImport], function(d) {return d;});
return maximum;
}
d3.json('/file_name.json', function(error, json) {
if (error) throw error;
let data = json;
let maximum = calcMaximum(data);
let scaleRadius = d3.scaleSqrt().domain([0, maximum]).range([0,150]);
}
I have created the following function to replace the duplicated code:
function calculateMaxByYear(json, activity) {
json.map(function (obj) {
let maxByYear = [];
obj.entries.map( function(entry) {
maxByYear.push(parseFloat(entry[activity]));
})
let maximus = d3.max(maxByYear, function(d) { return d; });
return maximus;
})
};
which in a synchronous way might be called calculateMaxByYear(json, 'imported');
calculateMaxByYear(json, 'exported');
, but I don't know how to use it in an asynchronous way.
Any ideas on how to solve this are very welcomed!
Thanks a lot!