From 0575e96b60fd760e0994a574ed6c8fcf0410312c Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Thu, 26 Nov 2009 14:21:09 -0500 Subject: [PATCH] Added commonPrefixWithString method to CPString and tests for it. --- Foundation/CPString.j | 38 +++++++++++++++++++++++++++++++++ Tests/Foundation/CPStringTest.j | 26 ++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/Foundation/CPString.j b/Foundation/CPString.j index 7ee5d08b9..30b6503c2 100644 --- a/Foundation/CPString.j +++ b/Foundation/CPString.j @@ -537,6 +537,44 @@ var CPStringRegexSpecialCharacters = [ return hash; } +/*! + Returns a string containing characters the receiver and a given string have in common, starting from + the beginning of each up to the first characters that aren't equivalent. + @param aString the string with which to compare the receiver +*/ +- (CPString)commonPrefixWithString:(CPString)aString +{ + return [self commonPrefixWithString: aString options: 0]; +} + +/*! + Returns a string containing characters the receiver and a given string have in common, starting from + the beginning of each up to the first characters that aren't equivalent. + @param aString the string with which to compare the receiver + @param aMask options for comparision +*/ +- (CPString)commonPrefixWithString:(CPString)aString options:(int)aMask +{ + var len = 0, // length of common prefix + min = MIN([aString length], [self length]); + + for ( len = 0; len < min; len++ ) + { + var lhs = [self characterAtIndex: len], + rhs = [aString characterAtIndex: len]; + + if (aMask & CPCaseInsensitiveSearch) + { + lhs = [lhs lowercaseString]; + rhs = [rhs lowercaseString]; + } + + if ( lhs != rhs ) + break; + } + return [self substringToIndex: len]; +} + /*! Returns a copy of the receiver with all the first letters of words capitalized. */ diff --git a/Tests/Foundation/CPStringTest.j b/Tests/Foundation/CPStringTest.j index cc7455f8f..3c5dd14d8 100644 --- a/Tests/Foundation/CPStringTest.j +++ b/Tests/Foundation/CPStringTest.j @@ -151,6 +151,32 @@ [self assert:[testStrings[i][0] boolValue] equals:testStrings[i][1]]; } +- (void)testCommonPrefixWithString +{ + var testStringsCase = [ + ["Hello", "Helicopter", "Hel"], + ["Tester", "Taser", "T"], + ["Abcd", "Abcd", "Abcd"], + ["A long string", "A longer string", "A long"] + ]; + + var testStringsCaseless = [ + ["hElLo", "HeLiCoPtEr", "hEl"], + ["tEsTeR", "TaSeR", "t"], + ["aBcD", "AbCd", "aBcD"], + ["a LoNg StRiNg", "A lOnGeR sTrInG", "a LoNg"] + ]; + + for (var i = 0; i < testStringsCase.length; i++) + [self assert: [testStringsCase[i][0] commonPrefixWithString:testStringsCase[i][1]] + equals: testStringsCase[i][2]]; + + for (var i = 0; i < testStringsCaseless.length; i++) + [self assert: [testStringsCaseless[i][0] commonPrefixWithString: testStringsCaseless[i][1] + options: CPCaseInsensitiveSearch] + equals: testStringsCaseless[i][2]]; +} + - (void)testCapitalizedString { var testStrings = [