javascript - D3: What is a Bisector? -
i'm looking making charts d3, , stumbled upon d3.bisector
. however, don't understand or documentation.
almost examples find in web use date array, similar example in official documentation:
var data = [ {date: new date(2011, 1, 1), value: 0.5}, {date: new date(2011, 2, 1), value: 0.6}, {date: new date(2011, 3, 1), value: 0.7}, {date: new date(2011, 4, 1), value: 0.8} ]; var bisect = d3.bisector(function(d) { return d.date; }).right;
so bisector do, besides picking date object array elements? *.right
return?
and of use if have simple 1-dimensional array, var data = [3, 6, 2, 7, 5, 4, 8]
?
thanks enlightening me.
the underlying idea behind bisect
this:
consider array mention - var data = [3, 6, 2, 7, 5, 4, 8]
you want insert new value let's 3.5
data
array , want know how 'partition' it. in other words, want know index of 3.5
if inserted when data
array sorted.
var data = [3, 6, 2, 7, 5, 4, 8] //sorted data [2, 3, 4, 5, 6, 7, 8] //you want insert 3.5 sorted array after insertion of 3.5 should like: [2, 3, 3.5, 4, 5, 6, 7, 8] index of 3.5 in sorted data array "2".
there situations want know how insertion of element 'bisects' or 'divides' array. in case, want first sort array , call binary search find out correct position insertion of element.
bisectleft
, bisectright
take care clarify anomaly in situation want enter element exists in array. let's want enter 3
array. there 2 situations:
3* -> new element entered [2, 3*, 3, 4, 5, 6, 7, 8] -> entered @ "1" (array still sorted) [2, 3, 3*, 4, 5, 6, 7, 8] -> entered @ "2" (array still sorted)
so depending upon how take care of ambiguity, can enter element 'left' or 'right' of existing element. docs (mark emphasis):
the returned insertion point partitions array 2 halves v < x v in array.slice(lo, i) left side , v >= x v in array.slice(i, hi) right side.
in bisectleft
1 suitable index, duplicate entries will on right of index , situation opposite in bisecright
.
now know how bisectleft
, bisectright
work, bisector
allows define custom comparator
or accessor
function parition values or make sense of < , > on objects well.
so piece of code:
var bisect = d3.bisector(function(d) { return d.date; }).right; var bisect = d3.bisector(function(a, b) { return a.date - b.date; }).right;
just specifies use bisectright
option , return suitable index insertion of element assuming array sorted(in ascending order).
so if build on example , assuming bisector
named bisect
. , did:
bisect(data, 3); //it return 2.
i hope clarifies things , gets started in right direction.
Comments
Post a Comment