Solution:
Change the line
let $submenuLength = $( this ).parent().find( '.sub-menu' ).children().length;
to
let $submenuLength = $( this ).parent().find( '.sub-menu:not(.specific-child)' ).children().length;