Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Add util methods for array.indexOf and array.remove.

  • Loading branch information...
commit c3517e7703ab9a1335db8a3d0974b045ae3107e5 1 parent 3ae88d1
@agrieve agrieve authored
Showing with 57 additions and 0 deletions.
  1. +24 −0 lib/common/utils.js
  2. +33 −0 test/test.utils.js
View
24 lib/common/utils.js
@@ -32,6 +32,30 @@ utils.defineGetter = function(obj, key, func) {
}
};
+utils.arrayIndexOf = function(a, item) {
+ if (a.indexOf) {
+ return a.indexOf(item);
+ }
+ var len = a.length;
+ for (var i = 0; i < len; ++i) {
+ if (a[i] == item) {
+ return i;
+ }
+ }
+ return -1;
+};
+
+/**
+ * Returns whether the item was found in the array.
+ */
+utils.arrayRemove = function(a, item) {
+ var index = utils.arrayIndexOf(a, item);
+ if (index != -1) {
+ a.splice(index, 1);
+ }
+ return index != -1;
+};
+
/**
* Returns an indication of whether the argument is an array or not
*/
View
33 test/test.utils.js
@@ -22,6 +22,39 @@
describe("utils", function () {
var utils = require('cordova/utils');
+ describe("utils.arrayIndexOf", function() {
+ it("should return -1 when not found", function() {
+ expect(utils.arrayIndexOf([1,2,3], 4)).toBe(-1);
+ });
+ it("should return 0 for first item", function() {
+ expect(utils.arrayIndexOf([1,2,3], 1)).toBe(0);
+ });
+ it("should return 2 for last item", function() {
+ expect(utils.arrayIndexOf([1,2,3], 3)).toBe(2);
+ });
+ it("should return index of first occurance", function() {
+ expect(utils.arrayIndexOf([1,2,1], 1)).toBe(0);
+ });
+ });
+
+ describe("utils.arrayRemove", function() {
+ it("should return true when removed.", function() {
+ var a = [1, 2, 3];
+ expect(utils.arrayRemove(a, 2)).toBe(true);
+ expect(a).toEqual([1, 3]);
+ });
+ it("should return false when item was not there.", function() {
+ var a = [1, 2, 3];
+ expect(utils.arrayRemove(a, 4)).toBe(false);
+ expect(a).toEqual([1, 2, 3]);
+ });
+ it("should remove only first occurance", function() {
+ var a = [1, 2, 1];
+ expect(utils.arrayRemove(a, 1)).toBe(true);
+ expect(a).toEqual([2, 1]);
+ });
+ });
+
describe("when cloning", function () {
it("can clone an array", function () {
var orig = [1, 2, 3, {four: 4}, "5"];
Please sign in to comment.
Something went wrong with that request. Please try again.