Skip to content

Commit

Permalink
Path to Section: rank matches on matched string length (#24296)
Browse files Browse the repository at this point in the history
* Path to Section: add a failing test

* Path to Section: correct a wrong test

* Path to Section: fix failing tests by ranking matches on matched string length

* Path to Section: address a few review comments
  • Loading branch information
lsinger authored Apr 19, 2018
1 parent 8ec2cba commit 750eafc
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
24 changes: 19 additions & 5 deletions client/lib/path-to-section/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import config from 'config';
import { find, startsWith } from 'lodash';
import { filter, get, max, maxBy, startsWith } from 'lodash';

/**
* Conditional dependency
Expand All @@ -17,15 +17,29 @@ const sections = config( 'project' ) === 'wordpress-com' ? require( 'wordpress-c
*
* f( '/' ) === 'reader"
* f( '/me' ) === 'me"
* f( '/me/account' ) === 'me"
* f( '/me/account' ) === 'account"
* f( '/read' ) === 'reader'
*/
export const wpcomImplementation = path => {
const match = find( sections, section =>
section.paths.some( sectionPath => startsWith( path, sectionPath ) )
// rank matches by the number of characters that match so e.g. /media won't map to /me
const bestMatch = maxBy( sections, section =>
max(
section.paths.map(
sectionPath => ( startsWith( path, sectionPath ) ? sectionPath.length : 0 )
)
)
);

return match && match.name;
// sort out special case we don't want to match: matching on '/' but path isn't exactly '/'
const matchingPaths = filter( bestMatch.paths, sectionPath => startsWith( path, sectionPath ) );
if ( matchingPaths.length === 1 && matchingPaths[ 0 ] === '/' && path !== '/' ) {
return null;
}
// make sure the best match is actually a match (in case nothing matches)
if ( bestMatch.paths.some( sectionPath => startsWith( path, sectionPath ) ) ) {
return get( bestMatch, 'name' );
}
return null;
};

/*
Expand Down
7 changes: 6 additions & 1 deletion client/lib/path-to-section/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,14 @@ describe( 'pathToSection', () => {
test( 'should correctly associate paths that start with the same string', () => {
expect( wpcomImplementation( '/themes' ) ).to.equal( 'themes' );
expect( wpcomImplementation( '/theme' ) ).to.equal( 'theme' );
expect( wpcomImplementation( '/media' ) ).to.equal( 'media' );
expect( wpcomImplementation( '/me' ) ).to.equal( 'me' );
} );
test( 'should handle deep paths', () => {
expect( wpcomImplementation( '/me/account' ) ).to.equal( 'me' );
expect( wpcomImplementation( '/me/account' ) ).to.equal( 'account' );
} );
test( 'should return null if unsuccessful', () => {
expect( wpcomImplementation( '/a-nonexistent-path' ) ).to.equal( null );
} );
} );

Expand Down

0 comments on commit 750eafc

Please sign in to comment.