utils.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import d3 from 'd3';
  2. // adapted from memoize.js by @philogb and @addyosmani
  3. export function memoize(fn) {
  4. return function () {
  5. var args = Array.prototype.slice.call(arguments);
  6. var key = "", len = args.length, cur = null;
  7. while (len--) {
  8. cur = args[len];
  9. key += (cur === Object(cur))? JSON.stringify(cur): cur;
  10. fn.memoize || (fn.memoize = {});
  11. }
  12. return (key in fn.memoize)? fn.memoize[key]:
  13. fn.memoize[key] = fn.apply(this, args);
  14. };
  15. }
  16. export function debounce(func, wait, immediate) {
  17. var timeout;
  18. return function() {
  19. var context = this, args = arguments;
  20. var later = function() {
  21. timeout = null;
  22. if (!immediate) {
  23. func.apply(context, args);
  24. }
  25. };
  26. var callNow = immediate && !timeout;
  27. clearTimeout(timeout);
  28. timeout = setTimeout(later, wait);
  29. if (callNow) {
  30. func.apply(context, args);
  31. }
  32. };
  33. }
  34. export var getTween = function (prop, to, time) {
  35. time = time || 500;
  36. var node = this;
  37. var curr = node[prop];
  38. var interpol = d3.interpolateObject(curr, to);
  39. return function (t) {
  40. node[prop].copy(interpol(t / time));
  41. if (t >= time) {
  42. return true;
  43. }
  44. };
  45. };