Added the logic to handle when array is null.

This commit is contained in:
Ziang Song 2013-02-15 14:58:32 -05:00
commit 99cf4bfe01
2 changed files with 17 additions and 4 deletions

View file

@ -1,10 +1,10 @@
describe('Kiwi.compose', function() { 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 = ""; var input = "";
expect(Kiwi.compose(input)).toEqual(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"; var input = "text without interpolation";
expect(Kiwi.compose(input)).toEqual(input); expect(Kiwi.compose(input)).toEqual(input);
}); });
@ -44,4 +44,10 @@ describe('Kiwi.compose', function() {
var result = "The rate is 2.3%"; var result = "The rate is 2.3%";
expect(Kiwi.compose(input, ["rate"])).toEqual(result); 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);
});
}); });

View file

@ -2,9 +2,12 @@ var Kiwi = (function ($) {
var TRANSPOSE_CHAR = '%'; var TRANSPOSE_CHAR = '%';
var interpolate = function(text, array){ var interpolate = function(text, array){
if(array === undefined) return text;
var stringToReturn = "" var stringToReturn = ""
,length = text.length ,length = text.length
,index = 0; ,index = 0
,array_length = array.length;
for(var i = 0; i < length; i++){ for(var i = 0; i < length; i++){
var currentChar = text[i]; var currentChar = text[i];
@ -16,7 +19,11 @@ var Kiwi = (function ($) {
i += 1; i += 1;
}else{ }else{
if(currentChar === TRANSPOSE_CHAR){ if(currentChar === TRANSPOSE_CHAR){
stringToReturn += array[index++]; if(index < array_length){
stringToReturn += array[index++];
}else{
stringToReturn += '';
}
} }
else{ else{
stringToReturn += currentChar; stringToReturn += currentChar;