javascript - Why should I use immutablejs over object.freeze? -
i have researched on net benefits of immutablejs on object.freeze()
didn't find satisfying!
my question why should use library , work non native data structures when can freeze plain old javascript object?
i don't think understood immutablejs offers. it's not library turns objects immutable, it's library around working immutable values.
without repeating docs , mission statement, i'll state 2 things provides:
types. implemented (immutable) infinite ranges, stacks, ordered sets, lists, ...
all of types implemented persistent data structures.
i lied, here's quote of mission statement:
immutable data cannot changed once created, leading simpler application development, no defensive copying, , enabling advanced memoization , change detection techniques simple logic. persistent data presents mutative api not update data in-place, instead yields new updated data.
i urge read articles , videos link , more persistent data structures (since they're the thing immutablejs about), i'll summarise in sentence or so:
let's imagine you're writing game , have player sits on 2d plane. here, instance, bob:
var player = { name: 'bob', favouritecolor: 'moldy mustard', x: 4, y: 10 };
since drank fp koolaid want freeze player (brrr! hope bob got sweater):
var player = object.freeze({ name: 'bob', ... });
and enter game loop. on every tick player's position changed. can't update player object since it's frozen, copy over:
function moveplayer(player, newx, newy) { return object.freeze(object.assign({}, player, { x: newx, y: newy })); }
that's fine , dandy, notice how useless copying we're making: on every tick, create new object, iterate on 1 of our objects , assign new values on top of them. on every tick, on every 1 of objects. that's quite mouthful.
immutable wraps you:
var player = immutable.map({ name: 'bob', ... }); function moveplayer(player, newx, newy) { return player.set('x', newx).set('y', newy); }
and through ノ*✧゚ magic ✧゚*ヽ of persistent data structures promise least amount of operations possible.
there difference of mindsets. when working "a plain old [frozen] javascript object" default actions on part of everything assume mutability, , have work mile achieve meaningful immutability (that's immutability acknowledges state exists). that's part of reason freeze
exists: when try otherwise, things panic. immutablejs immutability is, of course, default assumption , has nice api on top of it.
that's not all's pink , rosy cherry on top. of course, has downsides, , shouldn't cram immutable everywhere because can. sometimes, freeze
ing object enough. heck, of time that's more enough. it's useful library has niche, don't carried away hype.
Comments
Post a Comment