Skip to content

Commit

Permalink
add common-prefix util and use it in the list controller
Browse files Browse the repository at this point in the history
  • Loading branch information
meirish committed May 20, 2019
1 parent 82cedbb commit 04e0bbc
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
20 changes: 15 additions & 5 deletions ui/app/mixins/list-controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { computed } from '@ember/object';
import Mixin from '@ember/object/mixin';
import escapeStringRegexp from 'escape-string-regexp';
import commonPrefix from 'vault/utils/common-prefix';

export default Mixin.create({
queryParams: {
Expand All @@ -26,11 +27,20 @@ export default Mixin.create({
var content = this.get('model');
var filterMatchesKey = this.get('filterMatchesKey');
var re = new RegExp('^' + escapeStringRegexp(filter));
return filterMatchesKey
? null
: content.find(function(key) {
return re.test(key.get('id'));
});
let matchSet = content.filter(key => re.test(key.id));
let match = matchSet.firstObject;

if (filterMatchesKey || !match) {
return null;
}

let sharedPrefix = commonPrefix(content);
// if we already are filtering the prefix, then next we want
// the exact match
if (filter === sharedPrefix || matchSet.length === 1) {
return match;
}
return { id: sharedPrefix };
}),

actions: {
Expand Down
23 changes: 23 additions & 0 deletions ui/app/utils/common-prefix.js
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);
}

0 comments on commit 04e0bbc

Please sign in to comment.