Summary

Steps

data

순회 가능한 객체를 처리한다. 따라서 배열이 아닌 다른 객체도 data로 받을 수 있다.

d3.js 내부적으로는 length 속성이 있는 경우 이를 배열로 취급한다. 이외의 경우 Array.from()을 거쳐 해당 입력을 배열로 변환해 처리한다. 따라서 다음 자료형 모두 selection.data(data, key)에 입력으로 전달할 수 있다.

  • Map, Set
  • 제네레이터 함수
  • 유사 배열 객체

key

key는 DOM이나 data의 영구 속성이 아니라, 새로 얻은 데이터와 이미 존재하는 DOM 요소를 연결하기 위한 일시적인 규칙이므로 별도로 저장하지 않는다. 이후 바인딩 때 node.__data__와 새 데이터를 이용해 다시 계산한다.

Troubleshooting

이해를 돕기 위해 해당 코드를 직접 살펴보면 아래와 같다. 한국어 주석은 직접 추가했다.

import {Selection} from "./index.js";
import {EnterNode} from "./enter.js";
import constant from "../constant.js";
 
function bindIndex(parent, group, enter, update, exit, data) {
  var i = 0,
      node,
      groupLength = group.length,
      dataLength = data.length;
 
  // Put any non-null nodes that fit into update.
  // Put any null nodes into enter.
  // Put any remaining data into enter.
  for (; i < dataLength; ++i) {
    if (node = group[i]) {
      node.__data__ = data[i];
      update[i] = node;
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }
 
  // Put any non-null nodes that don’t fit into exit.
  for (; i < groupLength; ++i) {
    if (node = group[i]) {
      exit[i] = node;
    }
  }
}
 
function bindKey(parent, group, enter, update, exit, data, key) {
  var i,
      node,
      nodeByKeyValue = new Map,
      groupLength = group.length,
      dataLength = data.length,
      keyValues = new Array(groupLength),
      keyValue;
 
  // Compute the key for each node.
  // If multiple nodes have the same key, the duplicates are added to exit.
  for (i = 0; i < groupLength; ++i) {
    if (node = group[i]) {
      keyValues[i] = keyValue = key.call(node, node.__data__, i, group) + "";
      if (nodeByKeyValue.has(keyValue)) {
        exit[i] = node;
      } else {
        nodeByKeyValue.set(keyValue, node);
      }
    }
  }
 
  // Compute the key for each datum.
  // If there a node associated with this key, join and add it to update.
  // If there is not (or the key is a duplicate), add it to enter.
  for (i = 0; i < dataLength; ++i) {
    keyValue = key.call(parent, data[i], i, data) + "";
    if (node = nodeByKeyValue.get(keyValue)) {
      update[i] = node;
      node.__data__ = data[i];
      nodeByKeyValue.delete(keyValue);
    } else {
      enter[i] = new EnterNode(parent, data[i]);
    }
  }
 
  // Add any remaining nodes that were not bound to data to exit.
  for (i = 0; i < groupLength; ++i) {
    if ((node = group[i]) && (nodeByKeyValue.get(keyValues[i]) === node)) {
      exit[i] = node;
    }
  }
}
 
function datum(node) {
  return node.__data__;
}
 
// 실제로 내보내는 함수는 아래부터다.
export default function(value, key) {
 
  if (!arguments.length) return Array.from(this, datum);
	// 오버라이딩 함수이므로 인자가 있을 때는 setter, 
	// 위처럼 인자가 없을 때는 getter가 된다.
	// 따라서 인자가 없을 경우 바인딩된 데이터를 배열로 변환해 반환한다.
 
  var bind = key ? bindKey : bindIndex,
      parents = this._parents,
      groups = this._groups;
 
  if (typeof value !== "function") value = constant(value);
 
	// 아래는 이 메서드를 호출한 객체의 내부 속성을 먼저 순회하는 반복문이다.
	// 이 메서드를 호출한 객체는 d3.Selection 객체이다.
	
	// 따라서 아래 반복문은 현재 갖고 있는 DOM 요소를 먼저 순회하게 된다.
  for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) { // 우선 새로운 배열을 세 개 만든다.
    var parent = parents[j],
        group = groups[j],
        groupLength = group.length,
        data = arraylike(value.call(parent, parent && parent.__data__, j, parents)),
        dataLength = data.length,
        enterGroup = enter[j] = new Array(dataLength),
        updateGroup = update[j] = new Array(dataLength),
        exitGroup = exit[j] = new Array(groupLength);
 
    bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);
 
    // Now connect the enter nodes to their following update node, such that
    // appendChild can insert the materialized enter node before this node,
    // rather than at the end of the parent node.
    for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1) i1 = i0 + 1;
        while (!(next = updateGroup[i1]) && ++i1 < dataLength);
        previous._next = next || null;
      }
    }
  }
 
  update = new Selection(update, parents);
  update._enter = enter;
  update._exit = exit;
  return update;
}
 
// Given some data, this returns an array-like view of it: an object that
// exposes a length property and allows numeric indexing. Note that unlike
// selectAll, this isn’t worried about “live” collections because the resulting
// array will only be used briefly while data is being bound. (It is possible to
// cause the data to change while iterating by using a key function, but please
// don’t; we’d rather avoid a gratuitous copy.)
function arraylike(data) {
  return typeof data === "object" && "length" in data
    ? data // Array, TypedArray, NodeList, array-like
    : Array.from(data); // Map, Set, iterable, string, or anything else
}

References