I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.
Today I did: https://www.codewars.com/kata/deep-freeze/javascript
Time: 30 minutes
What I’ve learnt: So we had to freeze the first object and then the inner ones, so recursion was definitely called for. I used the javascript for in loop
which is a nice change from the regular for
loop which would not have worked well here. I got confused first trying to check if the item was an object, until I realized I needed to check the value of the object itself, and not the item alone (object[item]
). That’s what took me the longest time. I also tried to make it more concise after with reduce or map, but it really wasn’t necessary or cleaner, so left as is.
Here was my solution:
1 2 3 4 5 6 |
Object.deepFreeze = function (object) { Object.freeze(object) for (var property in object) { if (object[property] instanceof Object) Object.deepFreeze(object[property]) } } |
What I learned from other people’s code:
Seems like recursion was common practice here. typeof
is another way to check for an object
as opposed to instanceOf Object
. Happy to see no one used reduce or filter. 😉
Can’t wait for tomorrow’s challenge 🙂