Skip to content

Commit c993d97

Browse files
committed
fix(exact): Returning first and only if exact match
closes #4
1 parent 2fe4115 commit c993d97

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/find-scripts-spec.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ describe('find-scripts', function () {
33
const scripts = {
44
foo: 'foo',
55
bar: 'bar',
6+
barMore: 'bar-more',
67
baz: 'baz'
78
};
89

@@ -30,9 +31,16 @@ describe('find-scripts', function () {
3031
console.assert(found[0] === 'foo');
3132
});
3233

33-
it('finds 2', function () {
34+
it('finds several', function () {
3435
const found = find('b', scripts);
3536
console.assert(Array.isArray(found));
36-
console.assert(found.length === 2);
37+
console.assert(found.length === 3);
38+
});
39+
40+
it('finds an exact match if possible', function () {
41+
const found = find('bar', scripts);
42+
console.assert(Array.isArray(found));
43+
console.assert(found.length === 1, found);
44+
console.assert(found[0] === 'bar');
3745
});
3846
});

src/find-scripts.js

+18-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,27 @@
11
function startsWith(prefix, str) {
2+
console.assert(typeof str === 'string', 'expected string', str);
23
return str.indexOf(prefix) === 0;
34
}
45

6+
function sameLength(a, b) {
7+
return a.length === b.length;
8+
}
9+
10+
function matchesExactly(prefix, str) {
11+
return startsWith(prefix, str) &&
12+
sameLength(prefix, str);
13+
}
14+
515
function findScripts(prefix, scripts) {
16+
const labels = Object.keys(scripts);
17+
const matchesExactlyPrefix = matchesExactly.bind(null, prefix);
18+
const exactMatches = labels.filter(matchesExactlyPrefix);
19+
if (exactMatches.length === 1) {
20+
return exactMatches;
21+
}
22+
623
const startsWithPrefix = startsWith.bind(null, prefix);
7-
const matchingScripts = Object.keys(scripts).filter(startsWithPrefix);
24+
const matchingScripts = labels.filter(startsWithPrefix);
825
return matchingScripts;
926
}
1027

0 commit comments

Comments
 (0)