y.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import constant from "./constant.js";
  2. export default function(y) {
  3. var strength = constant(0.1),
  4. nodes,
  5. strengths,
  6. yz;
  7. if (typeof y !== "function") y = constant(y == null ? 0 : +y);
  8. function force(alpha) {
  9. for (var i = 0, n = nodes.length, node; i < n; ++i) {
  10. node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
  11. }
  12. }
  13. function initialize() {
  14. if (!nodes) return;
  15. var i, n = nodes.length;
  16. strengths = new Array(n);
  17. yz = new Array(n);
  18. for (i = 0; i < n; ++i) {
  19. strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
  20. }
  21. }
  22. force.initialize = function(_) {
  23. nodes = _;
  24. initialize();
  25. };
  26. force.strength = function(_) {
  27. return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  28. };
  29. force.y = function(_) {
  30. return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), initialize(), force) : y;
  31. };
  32. return force;
  33. }