Skip to content

Instantly share code, notes, and snippets.

@Shervin1995
Created November 19, 2022 23:12
Show Gist options
  • Save Shervin1995/ab25d7d4846140eb01b3f7aeb22dd57c to your computer and use it in GitHub Desktop.
Save Shervin1995/ab25d7d4846140eb01b3f7aeb22dd57c to your computer and use it in GitHub Desktop.
convert csv to list, bafore change DSA to tree via d3.stratify( )
// --------------------------------------------------------
// Step 1
// --------------------------------------------------------
var data = [{
country: "Iran", city: "Tehran", district: 22, size: 1200
},{
country: "Iran", city: "Tehran", district: 6, size: 1200
},{
country: "Iran", city: "Tehran", district: 5, size: 1200
},{
country: "Iran", city: "Kerman", district: 21, size: 130
},{
country: "Georgia", city: "Talbisi", district: 20, size: 100
}];
var main_columns = ["country", "city", "district"];
// var tooltip_columns = []
var generations = main_columns;
var genlen = generations.length;
if (genlen < 1) {
console.log("impossible");
}
var data1 = [{id: "null"}]
var ids = {}
generations.forEach(gen => ids[gen] = [])
// --------------------------------------------------------
// Step 2
// --------------------------------------------------------
function repeat(data, cb) {
var depth = genlen-1
var one = data[0]
//
function isIncluded(gen, id) {
if (ids[gen].includes(id)) {
return true
} else {
ids[gen].push(id)
return false
}
}
//
var data2 = generations.reduce((cur, gen, i) => {
var options = {};
switch (i) {
case 0:
var id = one[gen]
var parentId = "null"
if(depth == i) options = one
break;
case 1:
var id = one[generations[i-1]] + one[gen]
var parentId = one[generations[i-1]]
if(depth == i) options = one
break;
case depth:
var id = one[generations[i-1]] + one[gen]
var parentId = one[generations[i-2]] + one[generations[i-1]]
options = one
break;
default:
var id = one[generations[i-1]] + one[gen]
var parentId = one[generations[i-2]] + one[generations[i-1]]
break;
}
//
if(!isIncluded(gen, id)) cur.push({id, parentId, ...options})
return cur;
}, []);
//
data1 = [...data1, ...data2]
//
if (data[1]) {
data.shift();
repeat(data, cb)
} else {
cb(data1, ids)
}
}
// --------------------------------------------------------
// Step 3
// --------------------------------------------------------
repeat(data, (result, c) => {
console.log(result, c);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment