- Код: Выделить всё
const s = ['flower', 'flow', 'flight'],
a = ['sunday', 'sunny', 'sun'],
z = ['sunday', 'sunny', 'sun', 'cunning'];
function pref(arr){
if(!Array.isArray(arr) || !arr.length) return 'Wrong data passed';
const ar = arr.sort( (a, b) => a.length - b.length );
let found = '';
for(let n of ar[0]){
if(ar.every( x => x.at(ar[0].indexOf(n)) == n )){ found += n; }
else{ break; }
}
return found.length ? found : 'No common prefix found';
}
console.log( pref(s) ); // fl
console.log( pref(a) ); // sun
console.log( pref(z) ); // No common prefix found
console.log( pref([]) ); // Wrong data passed
console.log( pref('shit') ); // Wrong data passed
console.log( pref(['shit']) ); // shit