Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
meirish committed May 20, 2019
1 parent 04e0bbc commit e59fbe2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
9 changes: 5 additions & 4 deletions ui/app/utils/common-prefix.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,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
// this assumes an already sorted array
// if the array is sorted, we want to compare the first and last
// item in the array - if they share a prefix, all of the items do
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
// increment the prefixLength and try again
while (
prefixLength < targetLength &&
firstString.charAt(prefixLength) === lastString.charAt(prefixLength)
) {
prefixLength++;
}
// slice the prefix from the match
// slice the prefix from the first item
return firstString.substring(0, prefixLength);
}
27 changes: 27 additions & 0 deletions ui/tests/unit/utils/common-prefix-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import commonPrefix from 'vault/utils/common-prefix';
import { module, test } from 'qunit';

module('Unit | Util | common prefix', function() {
test('it returns empty string if there are no common prefixes', function(assert) {
let secrets = ['asecret', 'secret2', 'secret3'].map(s => ({id: s}));
let returned = commonPrefix(secrets);
assert.equal(returned, '', 'returns an empty string');
});

test('it returns the longest prefix', function(assert) {
let secrets = ['secret1', 'secret2', 'secret3'].map(s => ({id: s}));
let returned = commonPrefix(secrets);
assert.equal(returned, 'secret', 'finds secret prefix');
let greetings = ['hello-there', 'hello-hi', 'hello-howdy'].map(s => ({id: s}));
returned = commonPrefix(greetings);
assert.equal(returned, 'hello-', 'finds hello- prefix');
});


test('it can compare an attribute that is not "id" to calculate the longest prefix', function(assert) {
let secrets = ['secret1', 'secret2', 'secret3'].map(s => ({name: s}));
let returned = commonPrefix(secrets, 'name');
assert.equal(returned, 'secret', 'finds secret prefix from name attribute');
});
});

0 comments on commit e59fbe2

Please sign in to comment.