Search⌘ K
AI Features

Solution Review: Injecting Multiple Properties

Explore how to inject multiple properties into JavaScript objects using the defineProperties method. Understand how to create dynamic getters for integer and fractional parts of numbers, enhancing your metaprogramming skills with practical examples.

Solution

...
Node.js
'use strict';
Object.defineProperties(Number.prototype, {
integerPart: {
get: function() {
return this.toString().split('.')[0];
}
},
fractionalPart: {
get: function() { return this.toString().split('.')[1] || 0; }
}
});
const printParts = function(number) {
return `whole: ${number.integerPart} decimal: ${number.fractionalPart}`;
};
console.log(printParts(22.12)); //whole: 22 decimal: 12
console.log(printParts(.14)); //whole: 0 decimal: 14
console.log(printParts(-23.19)); //whole: -23 decimal: 19
console.log(printParts(42)); //whole: 42 decimal: 0
...