array.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Utilities: A classic collection of JavaScript utilities
  3. * Copyright 2112 Matthew Eernisse ([email protected])
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. /**
  19. @name array
  20. @namespace array
  21. */
  22. var array = new (function () {
  23. /**
  24. @name array#humanize
  25. @public
  26. @function
  27. @return {String} A string containing the array elements in a readable format
  28. @description Creates a string containing the array elements in a readable format
  29. @param {Array} array The array to humanize
  30. */
  31. this.humanize = function (a) {
  32. var array = a.slice();
  33. // If array only has one item then just return it
  34. if (array.length <= 1) {
  35. return String(array);
  36. }
  37. var last = array.pop()
  38. , items = array.join(', ');
  39. return items + ' and ' + last;
  40. };
  41. /**
  42. @name array#included
  43. @public
  44. @function
  45. @return {Array/Boolean} If `item` is included the `array` is
  46. returned otherwise false
  47. @description Checks if an `item` is included in an `array`
  48. @param {Any} item The item to look for
  49. @param {Array} array The array to check
  50. */
  51. this.included = function (item, array) {
  52. var result = array.indexOf(item);
  53. if (result === -1) {
  54. return false;
  55. } else {
  56. return array;
  57. }
  58. };
  59. /**
  60. @name array#include
  61. @public
  62. @function
  63. @return {Boolean} Return true if the item is included in the array
  64. @description Checks if an `item` is included in an `array`
  65. @param {Array} array The array to check
  66. @param {Any} item The item to look for
  67. */
  68. this.include = function (array, item) {
  69. var res = -1;
  70. if (typeof array.indexOf == 'function') {
  71. res = array.indexOf(item);
  72. }
  73. else {
  74. for (var i = 0, ii = array.length; i < ii; i++) {
  75. if (array[i] == item) {
  76. res = i;
  77. break;
  78. }
  79. }
  80. }
  81. return res > -1;
  82. };
  83. })();
  84. module.exports = array;