There is a definitiveness to the drop
method in that the number
parameter has to be a valid index since everything to the left is being truncated. An invalid index will not give us a result we would normally expect.
In this case we would definitely not be using loose relational analysis since, a) we are looking for strictly an integer; and, b) zero is a valid index and NOT would foul that.
Not even comparing to undefined
solves this criterion. It must be a number that we can use in the slice()
method. Note that negative indices are allowed. str.slice(-1)
will be the last character in the string.
drop()
doesn’t care what the contents of the array are, whether homogenous or fixed type. It does depend on a valid index, though. number
in this case must be a Number.
Consider a perfect world where data types are never an issue…
drop (array, n=1) {
return array.slice(n)
}
Where no n
is supplied that is no problem. What if n
is a bogus value that slice()
doesn’t recognize?
Do we build in try..catch
or do we validate logically? Do we expect that our program will validate before the call to this method? An in_range method would be in order for that validation.
Given that we’re using the slice()
method, our validation needs to take negative indices into account.
drop = (arr, number) => {
n = arr.length
fail = isNaN(number) // false if it looks like a number
pass = fail || +number >= -n && +number < n
// unary `+` coerces `Number` from `string` representation
if (pass) {
return arr.slice(+number)
} else {
return arr // no change
}
}
This is not rock hardened code, but it does lead the way…
One more consideration onto the pile…
return arr.slice(+number)
By this point we know we have a number or it wouldn’t have passed. That could be any number, though, and may have a decimal fraction which is useless to our cause. We can only use integers for indices.
To the rescue we bring in the cleanup crew to perfect this value for final use (replaces if structure).
return pass ? arr.slice(parseInt(number, 10)) : arr
In the above we don’t need to coerce Number since parseInt
does that for us. We’ve been threading a needle this whole way.