diff --git a/ex1/ex1.js b/ex1/ex1.js index 5eead9d..6d19e37 100644 --- a/ex1/ex1.js +++ b/ex1/ex1.js @@ -6,3 +6,21 @@ * fn(",,,") === 2 * fn("hel,lowo,rld") === -1 */ + +function getThirdCommaIndex(str,searchFor) { + + var index = -1; + + for (var i = 0; i < 3; i++) { + + index = str.indexOf(searchFor, index + 1); + + // If we did not find a comma in str will stop searching + if (index == -1) { + break; + } + } + return index; +} + +module.exports = getThirdCommaIndex; diff --git a/ex1/ex1Spec.js b/ex1/ex1Spec.js new file mode 100644 index 0000000..3c5310c --- /dev/null +++ b/ex1/ex1Spec.js @@ -0,0 +1,19 @@ +var getThirdCommaIndex = require("./ex1"); + +describe("function getThirdCommaIndex", function() { + + it("returns -1 when no third comma", function() { + expect(getThirdCommaIndex('hel,lowo,rld', ',')) + .toBe(-1); + }); + + it("finds a comma in a regular sentence", function() { + expect(getThirdCommaIndex('hello,world,this,is,a,great,day', ',')) + .toBe(16); + }); + + it("works even when there are no characters beside commas", function() { + expect(getThirdCommaIndex(',,,', ',')) + .toBe(2); + }); +});