amitguptagwl avatar

Fast Freeze - Make an object read only in Javascript

amitguptagwl

Published: 02 Sept 2018 › Updated: 02 Sept 2018Fast Freeze - Make an object read only in Javascript

Fast Freeze - Make an object read only in Javascript

Repository

https://github.com/node-muneem/fast-freeze

About

I was working to create a fast, secure web framework in nodejs, where I had to freeze configuration object so that any accidental change in the configuration can be avoided. I tried many js libraries and Object.freeze() and Object.seal() methods available in javascript. They impacted the performance of the application badly. Hence I decided to create another tool which can protect original object from any delete or write operation. And I came up with fast-freeze.

How to use it

It's fairly simple to use. Install the npm package. And include it in your node module.( I'll generate the browser bundle in next few days.) Now pass the object in its method to freeze it. See below example;

var fastFreeze = require("fast-freeze");//import the package

var testConfig = {
    name: 'John',
    surname: 'Johnson',
    age: 26,
    address: {
        street: '1st Street',
        city: 'Los Angeles',
        country: 'USA'
    },
    vehicles: [
        'BMW',
        'Ferrari',
        'Lamborghini'
    ]
};

var frozenConfig = fastFreeze(testConfig);//freeze it

console.log( frozenConfig("vehicles")[1] );//access existing properties
console.log( testConfig["vehicles"][1] );//access existing properties from original object

When you freeze an object with fast-freeze library, it basically converts the object into a series of nested functions. As a result, accessing of any internal property becomes ugly but many times faster.

chart.png

The best thing is that it becomes faster than even direct access of the properties.

chart (1).png

Support

Though this library is very small and there is very less scope of new features, I welcome your suggestion and contribution.

Leave Fast Freeze - Make an object read only in Javascript to:

Written by

Read more #utopian-io posts


Best Posts From amitguptagwl

We have not curated any of amitguptagwl's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From amitguptagwl