Collections.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * Failsafe remove an element from a collection
  3. *
  4. * @param {Array<Object>} [collection]
  5. * @param {Object} [element]
  6. *
  7. * @return {Number} the previous index of the element
  8. */
  9. export function remove(collection, element) {
  10. if (!collection || !element) {
  11. return -1;
  12. }
  13. var idx = collection.indexOf(element);
  14. if (idx !== -1) {
  15. collection.splice(idx, 1);
  16. }
  17. return idx;
  18. }
  19. /**
  20. * Fail save add an element to the given connection, ensuring
  21. * it does not yet exist.
  22. *
  23. * @param {Array<Object>} collection
  24. * @param {Object} element
  25. * @param {Number} idx
  26. */
  27. export function add(collection, element, idx) {
  28. if (!collection || !element) {
  29. return;
  30. }
  31. if (typeof idx !== 'number') {
  32. idx = -1;
  33. }
  34. var currentIdx = collection.indexOf(element);
  35. if (currentIdx !== -1) {
  36. if (currentIdx === idx) {
  37. // nothing to do, position has not changed
  38. return;
  39. } else {
  40. if (idx !== -1) {
  41. // remove from current position
  42. collection.splice(currentIdx, 1);
  43. } else {
  44. // already exists in collection
  45. return;
  46. }
  47. }
  48. }
  49. if (idx !== -1) {
  50. // insert at specified position
  51. collection.splice(idx, 0, element);
  52. } else {
  53. // push to end
  54. collection.push(element);
  55. }
  56. }
  57. /**
  58. * Fail save get the index of an element in a collection.
  59. *
  60. * @param {Array<Object>} collection
  61. * @param {Object} element
  62. *
  63. * @return {Number} the index or -1 if collection or element do
  64. * not exist or the element is not contained.
  65. */
  66. export function indexOf(collection, element) {
  67. if (!collection || !element) {
  68. return -1;
  69. }
  70. return collection.indexOf(element);
  71. }