Skip to content

Instantly share code, notes, and snippets.

@DevGW
Last active April 5, 2023 14:35
Show Gist options
  • Save DevGW/3fd015de83c6203b6979a0307c2868e2 to your computer and use it in GitHub Desktop.
Save DevGW/3fd015de83c6203b6979a0307c2868e2 to your computer and use it in GitHub Desktop.
Javascript :: Object Methods #js
// define a method by putting the function after a property in an object:
let me = {
'name' : '',
getGreeting: function() {
return `Hi, my name is ${this.name}.`
}
}
me.name = 'Mary'
console.log(me.getGreeting());
>Hi, my name is Mary.
// you can pass in a parameter to use a property key in a method of the same object:
let me2 = {
name: 'Tarana',
getGreeting : function(friend) {
return 'Hi ' + friend.name + ', my name is ' + this.name + '.';
}
}
>Hi Alyssa, my name is Tarana.
// passing in a param object that contains methods and calling them with a value:
function callThemAll(object, value) {
let methodResults = [];
for (let key in object) {
let currObj = object[key];
if (typeof currObj === 'function') {
let methodResult = currObj(value);
methodResults.push(methodResult);
}
}
return methodResults;
}
//tic tac toe
let ticTacToe = {
board: [
[null, null, null],
[null, null, null],
[null, null, null],
],
move: function(player, rowNum, colNum) {
if (!this.board[rowNum][colNum]) {
this.board[rowNum][colNum] = player;
}
console.log(this.board);
return this.board
},
clear: function() {
this.board = [
[null, null, null],
[null, null, null],
[null, null, null],
];
console.log(this.board);
return this.board;
}
}
// inventory manager
let tacoCatInc = {
gourmetShell: {
'hard treat shell': {cost: 2, quantity: 100},
'soft treat shell': {cost: 1.5, quantity: 100}
},
gourmetFishFilling: {
'salmon': {cost: 5, quantity: 100},
'tuna': {cost: 5.5, quantity: 100},
'sardines': {cost: 1.5, quantity: 100}
},
gourmetVeggie: {
'cat grass': {cost: 1, quantity: 100}
},
gourmetSeasoning: {
'cat nip': {cost: 0.5, quantity: 100},
'treat dust': {cost: 0.1, quantity: 100}
},
cash: 0
};
// YOUR CODE BELOW
tacoCatInc.currentInventory = function () {
let total = 0;
for (let key in this) {
if (key === 'cash') {
continue;
}
let items = this[key];
for (let itemName in items) {
let itemObj = items[itemName];
total += itemObj.cost * itemObj.quantity;
}
}
return total;
};
tacoCatInc.sale = function(order) {
let finalPrice = 0;
for (let category in order) {
let choice = order[category];
finalPrice += this[category][choice].cost;
this.cash += this[category][choice].cost;
this[category][choice].quantity--;
}
return finalPrice;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment