Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
two loops
I like this!
This comment is hidden because it contains spoiler information about the solution
Looks smart but this can be done with 1 loop instead of the 2 you are using here.
this shouldn't be marked best practice.
This is my solution too more or less, and I agree with others that the clever ones are admirable and fun. But I want to be able to read and follow the code easily now or at any time in the future. The plodding, workmanlike solutions are the way forward.
There's no type coercion in
string > string
.Would it be good practice to convert to a number if you plan on working with TypeScript or if you don't want type-coersion related bugs in your code?
The brackets
[]
are a way of accessing an object's property called bracket notation.The more common way like
ops.propertyName
is called dot notation.I use bracket notation here because it allows you to use variables, and dot notation does not.
ops[operation]
returns the property value matchingoperation
if it exists, and undefined otherwise. The property value for + - * / are all function references.ops[operation]()
returns that function reference from the[]
and then knows to actually execute the function because of the()
. It's just like calling a method with dot notation. If you accidentally typeObject.method
instead ofObject.method()
, you get a function reference instead of executing the function.In my solutions it's not an IIFE because the function was defined inside of the object, then invoked later rather than immediately.
Can you pls explain what does
ops[operation]()
mean in this code, what is that bracket for? It can't be an IIFE since you're accessing it with an object..this is where I ended up. took a second but made the most sense to me. good work!
Necro-ing a 5 year old comment, but if you're still around could you explain what you mean? Seems you could make it work just fine without needing to pass arguments to the ops methods.
I learned a lot from this solution! After taking the time to understand it, I recreated a simplified version of it using es6.
a accumulates the array item values by adding them. That's the first +. The second + converts the array item b from a string into a number so it can be added to the accumulator a.
I'm not sure what the 'a + +(b)' in the reduce is doing exactly. And I'm not having luck finding an explination. Could you explain what happening there? Thank you :)
This is a great tip! Thanks for sharing.
Loading more items...