array_utils.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. function _parseId(id) {
  19. return id.replace(/[^\d|\.]/g, '').split('.').map(function (i) {return parseInt(i, 10);});
  20. }
  21. module.exports = {
  22. /**
  23. *
  24. * @param arr {Array}
  25. * @param id
  26. * @return result {Array}
  27. */
  28. uniqObjectsbyId: function (arr, id) {
  29. var result = [];
  30. arr.forEach(function (item) {
  31. var isIdPresent = result.someProperty(id, item[id]);
  32. if (!isIdPresent) {
  33. result.pushObject(item);
  34. }
  35. });
  36. return result;
  37. },
  38. /**
  39. * intersect two arrays and return the common values
  40. *
  41. * @param {Array} arr1 - first array
  42. * @param {Array} arr2 - second array
  43. * @return {Array} intersection - the intersection of arr1 and arr2
  44. */
  45. intersect: function (arr1, arr2) {
  46. var intersection = [];
  47. var shortest = arr1.length >= arr2.length ? arr2 : arr1;
  48. var longest = arr1.length >= arr2.length ? arr1 : arr2;
  49. shortest.forEach(function (entry) {
  50. longest.indexOf(entry) > -1 ? intersection.push(entry) : null;
  51. });
  52. return intersection;
  53. },
  54. /**
  55. * Callback for sorting models with `id`-property equal to something like version number: 'HDP-1.2.3', '4.2.52' etc
  56. *
  57. * @param {{id: string}} obj1
  58. * @param {{id: string}} obj2
  59. * @returns {number}
  60. */
  61. sortByIdAsVersion: function (obj1, obj2) {
  62. var id1 = _parseId(Em.get(obj1, 'id'));
  63. var id2 = _parseId(Em.get(obj2, 'id'));
  64. var lId1 = id1.length;
  65. var lId2 = id2.length;
  66. var limit = lId1 > lId2 ? lId2 : lId1;
  67. for (var i = 0; i < limit; i++) {
  68. if (id1[i] > id2[i]) {
  69. return 1;
  70. }
  71. if (id1[i] < id2[i]) {
  72. return -1;
  73. }
  74. }
  75. if (lId1 === lId2) {
  76. return 0
  77. }
  78. return lId1 > lId2 ? 1 : -1;
  79. }
  80. };