Why is my function not producing the desired result? - javascript

const character = {
name: 'Simon',
getCharacter() {
return this.name;
}
};
const giveMeTheCharacterNOW = character.getCharacter.bind(character);
console.log('?', giveMeTheCharacterNOW);
the answer should be like "? simon"
// How do you fix this issue?

Function#bind returns a function.
Just call the function.
const
character = {
name: 'Simon',
getCharacter() {
return this.name;
}
},
giveMeTheCharacterNOW = character.getCharacter.bind(character);
console.log('?', giveMeTheCharacterNOW());

const character = {
name: 'Simon',
getCharacter() {
return this.name;
}
};
const giveMeTheCharacterNOW = character.getCharacter();
console.log('?', giveMeTheCharacterNOW);

Related

Why does my use of javascript's reduce function return "undefined"

1) I've got an array of objects, called employees.
2) I'm trying to find the highest paid employee in the array.
3) I'm using Javascript's reduce function (inside function findHighestPaid) to do so.
4) Running findHighestPaid(employees) returns "undefined" when I expected it to return the object that has property name: Abelard.
Here's my code.
const employees = [
{
name: "Aziz",
salary: 17050,
},
{
name: "Angela",
salary: 17060,
},
{
name: "Abelard",
salary: 17070,
},
];
function findHighestPaid(arrayOfObjects) {
let myObject = {
name: "pretendEmployee",
salary: 17040,
};
arrayOfObjects.reduce(myFunction, myObject);
function myFunction(acc, item) {
let personSalary = item.salary;
let accSalary = acc.salary;
if (Math.sign(personSalary - accSalary) > 0) {
console.log(`returning object for ${item.name}`);
return item;
} else {
console.log(`returning object for ${acc.name}`);
return acc;
}
} // end myFunction
}
When I run findHighestPaid(employees) and look in console I see :
returning object for Aziz // (as I expected)
returning object for Angela // (as I expected)
returning object for Abelard // (as I expected)
undefined // (oh oh!!!)
Why does the reduce function return "undefined"?
the undefined that's being printed at the end is the return value of findHighestPaid() function that you run.
since you're not returning anything it's returning undefined.
if your goal is to see the return value of reduce() add a return statement to the function like this:
const employees = [
{
name: "Aziz",
salary: 17050,
},
{
name: "Angela",
salary: 17060,
},
{
name: "Abelard",
salary: 17070,
},
];
function findHighestPaid(arrayOfObjects) {
let myObject = {
name: "pretendEmployee",
salary: 17040,
};
return arrayOfObjects.reduce(myFunction, myObject);
function myFunction(acc, item) {
let personSalary = item.salary;
let accSalary = acc.salary;
if (Math.sign(personSalary - accSalary) > 0) {
console.log(`returning object for ${item.name}`);
return item;
} else {
console.log(`returning object for ${acc.name}`);
return acc;
}
} // end myFunction
}
console.log(findHighestPaid(employees));
Your code is working perfectly although you don't need Math.sign at all, just return the result:
const employees = [
{
name: "Aziz",
salary: 17050,
},
{
name: "Angela",
salary: 17080,
},
{
name: "Abelard",
salary: 17070,
},
];
function findHighestPaid(arrayOfObjects) {
let myObject = {
name: "pretendEmployee",
salary: 17040,
};
return arrayOfObjects.reduce(myFunction, myObject);
function myFunction(acc, item) {
let personSalary = item.salary;
let accSalary = acc.salary;
if (personSalary - accSalary > 0) {
console.log(`returning object for ${item.name}`);
return item;
} else {
console.log(`returning object for ${acc.name}`);
return acc;
}
} // end myFunction
}
console.log('Highest paid', findHighestPaid(employees));
you just have to put it like this
function findHighestPaid(arrayOfObjects) {
return arrayOfObjects.reduce((prev, curr) => {
if(!prev) {
return curr;
}
return curr.salary > prev.salary ? curr : prev;
}, null);
}
const highestPaidEmployee = findHighestPaid(employees);

Converting class to function

I'm making a real time app and want to convert this class code to a function.
Would the function below be the equivalent? And from what anyone can see, would there be a benefit to keeping it a class as opposed to a function?
class IdeaService {
constructor() {
this.ideas = [];
}
async find() {
return this.ideas;
}
async create(data) {
const idea = {
id: this.ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
this.ideas.push(idea);
return idea;
}
}
FUNCTION
function ideaService() {
let ideas = [];
async find() {
return ideas;
}
async create(data) {
const idea = {
id: ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
}
idea.time = moment().formate('h:mm:ss a');
ideas.push(idea);
return idea;
}
}
try this
let IdeaService = (function() {
let ideas = [];
async function find() {
return ideas;
}
async function create(data) {
const idea = {
id: ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
ideas.push(idea);
return idea;
}
return {
find,
create
}
})();
EDIT! If youd like this module to NOT be instantiated upon this file running remove the (); at the end. so the function would be:
IdeaService = (function() {
});
and to instantiate it would be:
let ideaService = IdeaService();

how to get an object from a closure?

How to get an object from a closure, that's confusion with me, here is the question:
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
question: How do i get original person object without changing the source code.
var o = function() {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function(key) {
return person[key]
}
}
}
Object.defineProperty(Object.prototype, "self", {
get() {
return this;
}
});
console.log(o().run("self")); // logs the object
This works as all objects inherit the Object.prototype, therefore you can insert a getter to it, which has access to the object through this, then you can use the exposed run method to execute that getter.
You can get the keys by running
o().run("<keyname>"))
Like that:
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
console.log(o().run("name"));
console.log(o().run("age"));
Could just toString the function, pull out the part you need, and eval it to get it as an object. This is pretty fragile though so getting it to work for different cases could be tough.
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
var person = eval('(' + o.toString().substr(30, 46) + ')')
console.log(person)
o().run("name")
It will be return "jonathan".
Simply you can make this
<script type="text/javascript">
var o = function () {
var person = {
name: 'jonathan',
age: 24
}
return {
run: function (key) {
return person[key]
}
}
}
let a = new o;
alert(a.run('name'));
</script>

Adding additional functions to object literals after it has been created

So I was wondering whether this is the right way to add functions to an object created through object literals.
var person = {
firstname: "default",
lastname: "default",
greet: function () {
return "hi " + this.firstname;
}
}
var me = Object.create(person);
me.myFunction = function() {
return console.log("meow");
};
console.log(me.myFunction());
However it returns an undefined after meow, is there any reason why it would do so?
When you write
return console.log("meow");
you don't return "meow", but the return value of console.log, which is undefined. Modify the code like this:
me.myFunction = function() {
return "meow";
};
console.log(me.myFunction());
console.log() doesn't return any value, so the "fallback" value of the function is undefined.
Since you're returning the return value of console.log and log that again, you get undefined.
All of this has nothing to do with modifying an object or a prototype.
You should return meow within myFunction:
var person = {
firstname: "default",
lastname: "default",
greet: function () {
return "hi " + this.firstname;
}
}
var me = Object.create(person);
me.myFunction = function() {
return "meow";
};
document.write(me.myFunction());
var person = {
firstname: "default",
lastname: "default",
greet: function () {
return "hi " + this.firstname;
}
}
var me = Object.create(person);
me.myFunction = function() {
return console.log("meow");
};
console.log(me.myFunction());
why you return console.log() it's return nothing

(Partial) Extending "functions" in javascript?

I have this code...
var my = {
helpers: {
getName: function() {
return 'John Doe';
}
}
}
// in another file...
var my = {
helpers: {
getAge: function() {
return '40';
}
}
}
// Test...
$("#myDiv").html(my.helpers.getName + " " + my.helpers.getAge);
http://jsfiddle.net/MojoDK/8cmV7/
... but getName is undefined.
I was hoping javascript was smart enough to merge it into this...
var my = {
helpers: {
getName: function() {
return 'John Doe';
},
getAge: function() {
return '40';
}
}
}
How do I extend a method (or what it's called) like above? I have several "helper" files, that needs to "merge".
Redundancy is good for this:
my = window.my || {};
my.helpers = my.helpers || {};
my.helpers.getAge = function() {
return 40;
};
Demo of it in action
You can also use http://api.jquery.com/jquery.extend
as in:
var my = {
getName: function() {}
};
$.extend(my, {
getAge: function() {
}
});
Demo: http://jsfiddle.net/7KW3H/

Categories

Resources