diff --git a/ui/app/utils/common-prefix.js b/ui/app/utils/common-prefix.js index b5e4fda6fdbf..e77d0569af74 100644 --- a/ui/app/utils/common-prefix.js +++ b/ui/app/utils/common-prefix.js @@ -2,8 +2,9 @@ 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); @@ -11,13 +12,13 @@ export default function(arr, attribute = 'id') { 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); } diff --git a/ui/tests/unit/utils/common-prefix-test.js b/ui/tests/unit/utils/common-prefix-test.js new file mode 100644 index 000000000000..0acc63ad76d1 --- /dev/null +++ b/ui/tests/unit/utils/common-prefix-test.js @@ -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'); + }); +}); +