Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: _.deepFreeze #4295

Closed
toshisugimo opened this issue May 16, 2019 · 3 comments
Closed

Feature request: _.deepFreeze #4295

toshisugimo opened this issue May 16, 2019 · 3 comments

Comments

@toshisugimo
Copy link

toshisugimo commented May 16, 2019

Hi!

I want to add a new function _.deepFreeze to lodash.

Pure javascript Object.freeze() does not freeze nested object.

const user = {
  name: 'Taro',
  age: 24,
  email: 'foo@example.com',
  location: {
    country: 'Japan',
    city: 'Tokyo'
  }
}

Object.freeze(user);

user.location.city = 'Kyoto';
// This will work. Because nested objects are not frozen.

console.log(user.location.city);
//=> 'Kyoto'
// Change from 'Tokyo' to 'Kyoto'

The _.deepFreeze function I want to propose also freezes nested objects.

const user = {
  name: 'Taro',
  age: 24,
  email: 'foo@example.com',
  location: {
    country: 'Japan',
    city: 'Tokyo'
  }
}

_.deepFreeze(user);

user.location.city = 'Kyoto';
// This will not work. user.location is immutable!
// TypeErrors will occur here if in strict mode.

console.log(user.location.city);
//=> 'Tokyo'
// Not changed

What do everyone think?
Thank you very much!

@ashclarke
Copy link

ashclarke commented May 17, 2019

Just a note of support as I have a custom implementation in place for this. There are probably better ways of doing it, but I have this:

function deepFreeze(object) {
    if (!_.isObjectLike(object)) {
        return;
    }

    Object.freeze(object);

    _.forOwn(object, function (value) {
        if (!_.isObjectLike(value) ||
            Object.isFrozen(value)) {

            return;
        }

        deepFreeze(value);
    });
}

@jdalton
Copy link
Member

jdalton commented May 18, 2019

Hi @toshisugimo!

I think something like this would be good on its own or in a suite of utils for immutability. For a reference implementation you can check out deep-freeze-strict.

@lock
Copy link

lock bot commented May 20, 2020

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators May 20, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Development

No branches or pull requests

3 participants