-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add common-prefix util and use it in the list controller
- Loading branch information
Showing
2 changed files
with
38 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import { get } from '@ember/object'; | ||
|
||
export default function(arr, attribute = 'id') { | ||
let content = arr || []; | ||
// this assumes an already sorted array, if we have a match, | ||
// it will have matched the first one so we also want the last one | ||
let firstString = get(content[0], attribute); | ||
let lastString = get(content[arr.length - 1], attribute); | ||
|
||
// the longest the shared prefix could be is the length of the match | ||
let targetLength = firstString.length; | ||
let prefixLength = 0; | ||
// walk the two strings, and if they match at the current length, | ||
// increment the prefix and try again | ||
while ( | ||
prefixLength < targetLength && | ||
firstString.charAt(prefixLength) === lastString.charAt(prefixLength) | ||
) { | ||
prefixLength++; | ||
} | ||
// slice the prefix from the match | ||
return firstString.substring(0, prefixLength); | ||
} |