Skip to content

Commit

Permalink
use public fields
Browse files Browse the repository at this point in the history
  • Loading branch information
leonid-shutov committed Jan 9, 2024
1 parent 41596cb commit 216f5c4
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 29 deletions.
23 changes: 13 additions & 10 deletions lib/strategies/from-keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@
/** @param {string[]} keys */
const fromKeys = (keys) => {
class MetaClass {
#privateFields;

constructor(argsObj) {
this.#privateFields = argsObj;

for (const field of keys) {
Object.defineProperty(MetaClass.prototype, field, {
get: () => this.#privateFields[field],
});
}
constructor(data) {
this.fields = data;
}
}

for (const field of keys) {
Object.defineProperty(MetaClass.prototype, field, {
get() {
return this.fields[field];
},
set(x) {
this.fields[field] = x;
},
});
}

return { metaClass: MetaClass, metaData: { keys: [...keys] } };
};

Expand Down
27 changes: 9 additions & 18 deletions meta-class.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,24 @@ describe("fromKeys strategy", () => {
const keys = ["name", "age", "color"];

const { metaClass: Cat, metaData } = MetaClass.fromKeys(keys);
const cat = new Cat({ name: "Sanya", age: 3, color: "Orange tabbie" });
const cat1 = new Cat({ name: "Sanya", age: 3, color: "Orange tabbie" });

it("Meta class is correct", () => {
assert.strictEqual(cat.name, "Sanya");
assert.strictEqual(cat.age, 3);
assert.strictEqual(cat.color, "Orange tabbie");
assert.strictEqual(cat1.name, "Sanya");
assert.strictEqual(cat1.age, 3);
assert.strictEqual(cat1.color, "Orange tabbie");
});

it("Meta data is correct", () => {
assert.deepStrictEqual(metaData.keys, keys);
assert.notStrictEqual(metaData.keys, keys);
});

it("Properties are frozen", () => {
const reassignName = () => {
cat.name = "Whiskers";
};
const reassignAge = () => {
cat.age = 5;
};
const reassignColor = () => {
cat.color = "black";
};

assert.throws(reassignName, TypeError);
assert.throws(reassignAge, TypeError);
assert.throws(reassignColor, TypeError);
it("It is possible to create more instances from the same class", () => {
const cat2 = new Cat({ name: "whiskers", age: 5, color: "Black" });
assert.strictEqual(cat2.name, "whiskers");
assert.strictEqual(cat2.age, 5);
assert.strictEqual(cat2.color, "Black");
});
});

Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"license": "MIT",
"main": "meta-class.js",
"types": "meta-class.d.ts",
"scripts": {
"test": "node --test"
},
"repository": {
"type": "git",
"url": "https://github.com/leonid-shutov/meta-class"
Expand All @@ -19,4 +22,4 @@
"@types/assert": "^1.5.10",
"@types/node": "^20.10.0"
}
}
}

0 comments on commit 216f5c4

Please sign in to comment.