as satisfying as this is, you're exposing a third argument that anyone can override. In a modern tech stack, this code is hesitantly admissible only if you can guarantee that absolutely no one can set length to be anything but end - start, otherwise you need to invest in a much more complex testing framework, likely outweighing the expense of adding a second line to this function.
I like this way:
As array from works with arrayLike structures and receives a second optional argument mapFn, it's a nice candidate to build range.
Yes, excellent solution.
This, slimmed down, version also works...
const range = (start, end) => Array.from({length: end}, (_, i) => start + 1);Sorry kerafyrm02, but that does not produce a range.
If I run range with range(1,50) I get [2,2,2,2,2,2,2,2,...]
const range = (start, end) => Array.from({length: end}, (_, i) => start + 1); console.log(range(0,20))let r = (s, e) => Array.from('x'.repeat(e - s), (_, i) => s + i);Ok here ya go... even shorter. :D
Rock, paper, scissors... 68 chars, you've nailed it!
lol., made
rangetor.. so even shorter :DTrust me to bump into a js golfer.
Next you'll be telling me that you're dropping the let keyword and just leaving r on the global object!!
haha! nice solution John!
Well, thank you so much for saying!
Almost.
Try:
as satisfying as this is, you're exposing a third argument that anyone can override. In a modern tech stack, this code is hesitantly admissible only if you can guarantee that absolutely no one can set
lengthto be anything butend - start, otherwise you need to invest in a much more complex testing framework, likely outweighing the expense of adding a second line to this function.Hi All, I'm trying to grasp this function:
But I still confused on why does passing { length } as first argument in Array.from is work to create new array with specific length.
Because what I read in the documentation about Array.from is only works for iterable or array like object.
Any explanation or help would be appreciate a lot. Thank you.
2 years too late to explain this. Hope it's not too late!
From the doc:
obj = { length: 10 }is:lengthpropertyobj[i]isundefinedfor any integeri.This is why
{ length }count as an "array-like" object. You could write in the long form:But it's not worth listing those entries out coz they are by default
undefinedanyways.