PageRenderTime 1852ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/functions/array/array_count_values.js

http://github.com/kvz/phpjs
JavaScript | 54 lines | 36 code | 3 blank | 15 comment | 9 complexity | 063da89753e11f213bfb4ffe0e6237dd MD5 | raw file
  1. function array_count_values (array) {
  2. // http://kevin.vanzonneveld.net
  3. // + original by: Ates Goral (http://magnetiq.com)
  4. // + namespaced by: Michael White (http://getsprink.com)
  5. // + input by: sankai
  6. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  7. // + input by: Shingo
  8. // + bugfixed by: Brett Zamir (http://brett-zamir.me)
  9. // * example 1: array_count_values([ 3, 5, 3, "foo", "bar", "foo" ]);
  10. // * returns 1: {3:2, 5:1, "foo":2, "bar":1}
  11. // * example 2: array_count_values({ p1: 3, p2: 5, p3: 3, p4: "foo", p5: "bar", p6: "foo" });
  12. // * returns 2: {3:2, 5:1, "foo":2, "bar":1}
  13. // * example 3: array_count_values([ true, 4.2, 42, "fubar" ]);
  14. // * returns 3: {42:1, "fubar":1}
  15. var tmp_arr = {},
  16. key = '',
  17. t = '';
  18. var __getType = function (obj) {
  19. // Objects are php associative arrays.
  20. var t = typeof obj;
  21. t = t.toLowerCase();
  22. if (t === "object") {
  23. t = "array";
  24. }
  25. return t;
  26. };
  27. var __countValue = function (value) {
  28. switch (typeof(value)) {
  29. case "number":
  30. if (Math.floor(value) !== value) {
  31. return;
  32. }
  33. // Fall-through
  34. case "string":
  35. if (value in this && this.hasOwnProperty(value)) {
  36. ++this[value];
  37. } else {
  38. this[value] = 1;
  39. }
  40. }
  41. };
  42. t = __getType(array);
  43. if (t === 'array') {
  44. for (key in array) {
  45. if (array.hasOwnProperty(key)) {
  46. __countValue.call(tmp_arr, array[key]);
  47. }
  48. }
  49. }
  50. return tmp_arr;
  51. }