From 99cf4bfe0193a5ef58c1a3745c3c3524d5e39f30 Mon Sep 17 00:00:00 2001 From: Ziang Song Date: Fri, 15 Feb 2013 14:58:32 -0500 Subject: [PATCH] Added the logic to handle when array is null. --- spec/KiwiSpec.js | 10 ++++++++-- src/Kiwi.js | 11 +++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/spec/KiwiSpec.js b/spec/KiwiSpec.js index 41742e9..6dbe729 100644 --- a/spec/KiwiSpec.js +++ b/spec/KiwiSpec.js @@ -1,10 +1,10 @@ describe('Kiwi.compose', function() { - it('should return the empty when input is empty',function() { + it('should return the empty string when input is empty',function() { var input = ""; expect(Kiwi.compose(input)).toEqual(input); }); - it('should return the input string',function() { + it('should return the input string when array is null',function() { var input = "text without interpolation"; expect(Kiwi.compose(input)).toEqual(input); }); @@ -44,4 +44,10 @@ describe('Kiwi.compose', function() { var result = "The rate is 2.3%"; expect(Kiwi.compose(input, ["rate"])).toEqual(result); }); + + it('should add empty string when size of the array is larger than the placeholders.', function() { + var input = "The quick brown % jumps % the lazy %."; + var result = "The quick brown fox jumps over the lazy ."; + expect(Kiwi.compose(input, ["fox", "over"])).toEqual(result); + }); }); \ No newline at end of file diff --git a/src/Kiwi.js b/src/Kiwi.js index 50d6fcd..46142fc 100644 --- a/src/Kiwi.js +++ b/src/Kiwi.js @@ -2,9 +2,12 @@ var Kiwi = (function ($) { var TRANSPOSE_CHAR = '%'; var interpolate = function(text, array){ + if(array === undefined) return text; + var stringToReturn = "" ,length = text.length - ,index = 0; + ,index = 0 + ,array_length = array.length; for(var i = 0; i < length; i++){ var currentChar = text[i]; @@ -16,7 +19,11 @@ var Kiwi = (function ($) { i += 1; }else{ if(currentChar === TRANSPOSE_CHAR){ - stringToReturn += array[index++]; + if(index < array_length){ + stringToReturn += array[index++]; + }else{ + stringToReturn += ''; + } } else{ stringToReturn += currentChar;