Alrogithm Challenge/Interview Question - Necessity of Thoroughness

Alrogithm Challenge/Interview Question - Necessity of Thoroughness
0
#1

Afternoon coders. I recently gave a shot at the Truncate String algorithm. I lost my mind, However The other day I watched a mock interview where this guy used methods really simply to write out his functions easily and effectively. Well it inspired me to rethink how I was approaching the algorithms too complexly.

So I took another shot at the truncate string and came up with:

function truncate( string, limiter ){
  return string.split(0, limiter-3).concat("...");
}

Now i’ve seen interview questions be a bit more simple. In this mock interview, the interviewee just focused on solving the question rather than covering all possible situations. So for example this is what would have passed.

Well not only does such an incomplete function not fly with me, it’s not enough to pass the challenges. So I ended up with this:

function truncateString(str, num) {
  if( str.length <= num || num === 0 ){ return str.slice(0, num); } // If string is less than limiter or limiter reduces string to nothing, do nothing.
  if( num > 3 ){ return str.slice(0, num-3).concat("..."); } // If limiter is greater than the truncate tail, count tail as deficit toward final length.
  else{ return str.slice(0, num).concat("..."); }
}

I’m wondering, are these if statements innappropriate? Ideally I’d use ECMAScript 5’s ternary conditions over these condition blocks, but is covering all situations like this more appropriate in an interview setting even if conditions are less graceful?

#3

In an interview setting, being able to identify and cover edge cases is a very important skill. I don’t think it’s less elegant per say, but that is up to the individual interviewer. Best thing to do is to ask them to clarify what input format is and discuss whether these corner cases should be handled.

#4

Ternary expressions were ECMAScript version 1, not version 5, they aren’t a new thing. And please don’t make this very common beginner error. Ternary expressions are often used (sparingly!) as a terse replacement for small pieces of logic expressed as if/else statements. But they don’t make your code somehow better: they generally sacrifice some readability for brevity. They are useful primarily because they are an expression, they aren’t just a thing you blindly replace if/else statements with.

#5

This is a very old post. I’ve come to know the purpose of ternary expressions. @dchenmei yes, it is good to ask the interviewer. If I recall this was a mock interview.