Skip to content

Instantly share code, notes, and snippets.

@sa-adebayo
Last active May 14, 2018 17:22
Show Gist options
  • Save sa-adebayo/02e1afc3353c240a95a6df15f7339bd0 to your computer and use it in GitHub Desktop.
Save sa-adebayo/02e1afc3353c240a95a6df15f7339bd0 to your computer and use it in GitHub Desktop.
Proxy that makes immutable object accessible via dot-notation (hack!)
const Immutable = require('immutable');
const immutableProfile = Immutable.fromJS({
data: [
{
name: 'Adebayo Akinlaja',
gender: 'Male',
properties: {
eyeColor: 'Blue',
skinColor: 'Black',
hairColor: 'Black',
},
skills: ['programming', 'karate', 'boxing', 'writing'],
},
{
name: 'Rex Ogbemudia',
gender: 'Male',
properties: {
eyeColor: 'Green',
skinColor: 'Brown',
hairColor: 'Brown',
},
skills: ['programming', 'kung-fu', 'car race', 'reading'],
},
],
totalRecords: 5,
totalPages: 3,
currentPage: 1,
pageSize: 2,
list: {
lister: {
ball: 'Yes',
},
},
});
// Proxies
const proxify = object => {
const proxie = {
get(target, property) {
if (property === 'unwrap') {
return target;
}
const result = target.get(property);
if (typeof result !== 'object') {
return result;
}
return new Proxy(result, proxie);
},
};
return new Proxy(object, proxie);
};
console.log("Accessing properties the js way via proxy\n");
for (var person of proxify(immutableProfile).data.unwrap) {
const prox = proxify(person);
console.log("Name: ", prox.name, " \nGender: ", prox.gender, " \nEye: ", prox.properties.eyeColor, " \nSkin: ", prox.properties.skinColor, " \nHair: ", prox.properties.hairColor, " \nSkills: ", [...prox.skills.unwrap].join(", "), "\n\n");
}
console.log("Accessing properties the immutable way\n");
for (var person of immutableProfile.get("data")) {
console.log("Name: ", person.get("name"), " \nGender: ", person.get("gender"), " \nEye: ", person.get("properties").get("eyeColor"), " \nSkin: ", person.getIn(["properties", "skinColor"]), " \nHair: ", person.getIn(["properties", "hairColor"]), " \nSkills: ", [...person.get("skills")].join(", "), "\n\n");
}
// RESULT:
// ```
// Accessing properties the js way via proxy
// Name: Adebayo Akinlaja
// Gender: Male
// Eye: Blue
// Skin: Black
// Hair: Black
// Skills: programming, karate, boxing, writing
// Name: Rex Ogbemudia
// Gender: Male
// Eye: Green
// Skin: Brown
// Hair: Brown
// Skills: programming, kung-fu, car race, reading
// Accessing properties the immutable way
// Name: Adebayo Akinlaja
// Gender: Male
// Eye: Blue
// Skin: Black
// Hair: Black
// Skills: programming, karate, boxing, writing
// Name: Rex Ogbemudia
// Gender: Male
// Eye: Green
// Skin: Brown
// Hair: Brown
// Skills: programming, kung-fu, car race, reading
// ```
@sa-adebayo
Copy link
Author

I believe it isn't clean enough so I suggest that you make it better if you can.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment