## Where communities thrive

• Join over 1.5M+ people
• Join over 100K+ communities
• Free without limits
##### Activity
• Dec 21 2018 17:11
• Jun 05 2018 23:13
• May 25 2018 16:50
Julian Gonggrijp
@jgonggrijp
@tundeiness Could you show the relevant bits of HTML and CSS? That's a bit easier talking.
Marco Colia
@justoverclockl
hello guys how can i sum all numbers inside a for loop?

function sumUntil(maxValue) {
let total = 0;
for (let i = 1; i <= maxValue; i++) {
console.log(i)

}
}

console.log(sumUntil(5));
i want the result 1 + 2 + 3 + 4 + 5
i'm trying to understand loop
Stephen James
@sjames1958gm
@justoverclockl looks like you need to add i to total value in the loop, e.g. total += i
Gianfabio Pezzolla
@gianfabiopezzolla
@justoverclockl @sjames1958gm has rights, you need to loop in this way to reach your goal:
var sum = 0;
function sumUntil(maxValue) {
for (let i = 1; i <= parseInt(maxValue); i++) {
sum += i;
}
}
const total = sumUntil(5)

console.log(sum);
// 15
Marco Colia
@justoverclockl
oh now is more clear, thanks
but why parseInt? we know that values are integer
and, what if i want this output? console.log(sumUntil(5)); // OUTPUT: 1 + 2 + 3 + 4 + 5 = 15
Marco Colia
@justoverclockl
@gianfabiopezzolla sono italiano comunque, grazie :D
Gianfabio Pezzolla
@gianfabiopezzolla
@justoverclockl Ciao Marco, di nulla figurati...
18 replies
Julian Gonggrijp
@jgonggrijp

I don't want to ruin your learning experience with regard to loops, but you can calculate the sum of a linear series of numbers using a formula. No need to iterate over all the numbers. :-)

function sumSeries(first, last, stride = 1) {
const length = (last - first) / stride + 1;
return (first + last) * length / 2;
}

How to use:

// sum of [1, 2, 3, 4, 5]
sumSeries(1, 5)

// sum of [5, 8, 11, 14] (step size 3)
sumSeries(5, 14, 3)

Credit due to Carl Friedrich Gauss (who was not the first to invent it).

Julian Gonggrijp
@jgonggrijp
Marco Colia
@justoverclockl
i'm stucked on some getter and setter

const person = {
get firstName() {
return this.firstName;
},
set firstName(value) {
this.firstName = value;
},
get lastName() {
return this.lastName;
},
set lastName(value) {
this.lastName = value;
},
fullName() {
return ${this.firstName}${this.lastName}
},
}

console.log(john.fullName()); // John Doe
console.log(simon.fullName()); // Simon Collins

/*
# Object Constructor - Exercise 1
Create the person object and define the methods within it
getter / setter for the properties: firstName and lastName.
Also define the fullName () method within the object
which takes care of concatenating and returning the name and surname
of the person. Finally, construct two objects: john and simon,
both go to the value of firstName and lastName
and print the full name in the console
*/
how can i achieve the expected output?
if anyone can show a commented solution will be appreciated
Julian Gonggrijp
@jgonggrijp

@justoverclockl The reason your code doesn't work is that you are writing functions that keep infinitely calling themselves. To see why this is the case, let's take a moment to see how getters and setters work.

Normally when you write anObject.firstName, it literally means "give me the value of the firstName property of anObject". Likewise, when you write anObject.firstName = 'John', it means "set the value of the firstName property of anObject to 'John'".

Getters and setters change this. If you define a getter for firstName, this means that the firstName property of anObject is now a function. When you write anObject.firstName, this function is implicitly called and the result is returned. Likewise, if you define a setter for firstName, writing anObject.firstName = 'John' actually means that you are passing 'John' as an argument to a function.

In your code, you are doing this:

const person = {
get firstName() {
return this.firstName;
},
// ...
};

The middle line return this.firstName is implicitly calling the getter function itself. Which you just defined to run that middle line. So this will repeat in itself and never end. The other accessors have the same problem.

The way to fix this is to have a separate property that will hold the actual data. A common practice is to use the same name but with an underscore before it. In that case, your person object will look like this:

const person = {
get firstName() {
return this._firstName;
},
set firstName(value) {
this._firstName = value;
},
get lastName() {
return this._lastName;
},
set lastName(value) {
this._lastName = value;
},
fullName() {
return ${this.firstName}${this.lastName}
},
};

Now you can create objects that inherit these accessors and the fullName method. You can supply the properties that hold the actual data while doing this. I'll show you the example for john:

const john = Object.create(person, {
_firstName: 'John',
_lastName: 'Doe',
});

For completeness, I'll mention that the use of accessors in this example is absolutely pointless. You can get the same result with less code and better performance if you just use regular properties:

const person = {
fullName() {
return ${this.firstName}${this.lastName};
},
};

const john = Object.create(person, {
firstName: 'John',
lastName: 'Doe',
});

Of course the exercise is still useful to get a grasp of how accessors work, but just remember that using them is not a goal in itself. You only need to spend code and effort on accessors if you need to perform extra work when a property is read or written, for example to ensure that multiple properties stay consistent with each other or to trigger events.

Julian Gonggrijp
@jgonggrijp

Oops, forgot that Object.create doesn't work exactly like _.create. You actually need to write this:

const john = Object.create(person, {
firstName: {value: 'John', writable: true},
lastName: {value: 'Doe', writable: true},
});

or this (using Underscore):

const john = _.create(person, {
firstName: 'John',
lastName: 'Doe',
});
This is a more interesting and useful way to use accessors:
const person = {
get fullName() {
return ${this.firstName}${this.lastName};
},
set fullName(full) {
const [first, last] = full.split(' ');
this.firstName = first;
this.lastName = last;
},
};

const john = _.create(person, {
firstName: 'John',
lastName: 'Doe',
});

console.log(john.fullName); // 'John Doe'

john.fullName = 'Joe Dalton';

console.log(john.firstName); // 'Joe'
console.log(john.lastName); // 'Dalton'
Marco Colia
@justoverclockl
wow thats a good material for me to make practice!!! thx
Marco Colia
@justoverclockl
guys, i need to filter out an array of object, and i want to return only the item that contain one or more "done" flag === false, but i can't access the nested object...it return undefined
const notes = [
{
id: 1,
description: 'Workout program',
todos: [
{
id: 1,
name: 'Push ups - 10 x 3',
done: false
},
{
id: 2,
name: 'Abdominals - 20 x 3',
done: true
},
{
id: 3,
name: 'Tapis Roulant - 15min',
done: true
}
]
},
{
id: 2,
todos: [
{
id: 1,
name: 'Learn HTML',
done: true
},
{
id: 2,
name: 'Learn CSS',
done: true
},
{
id: 3,
name: 'Learn JavaScript',
done: true
},
{
id: 4,
name: 'Learn Angular',
done: true
}
]
}
]

const filt = notes.filter((el) =>{
console.log(el.todos.done) // undefined
})

/* expected output

{
id: 1,
description: 'Workout program',
todos: [
{
id: 1,
name: 'Push ups - 10 x 3',
done: false                                        //this contain a false flag...so this object need to be returned
},
{
id: 2,
name: 'Abdominals - 20 x 3',
done: true
},
{
id: 3,
name: 'Tapis Roulant - 15min',
done: true
}
]
} */
seems that is possible with filter method and antoher method that is not map
Stephen James
@sjames1958gm

el.todos.done todos is an array and doesn't have a done property. You need to use another function on the todos array.
You can use the .any function to return true if any value in the array passes the function.
array.any(fn) where fn is passed the elements and if it returns true for any element .any return true.

notes.filter(note => notes.todos.any(todo => todo.done))

Gianfabio Pezzolla
@gianfabiopezzolla
@sjames1958gm .any is used in ruby, in js you need to use some
Gianfabio Pezzolla
@gianfabiopezzolla
@justoverclockl you can reach your goal with the following way:
const notes = [
{
id: 1,
description: 'Workout program',
todos: [
{
id: 1,
name: 'Push ups - 10 x 3',
done: false
},
{
id: 2,
name: 'Abdominals - 20 x 3',
done: true
},
{
id: 3,
name: 'Tapis Roulant - 15min',
done: true
}
]
},
{
id: 2,
todos: [
{
id: 1,
name: 'Learn HTML',
done: true
},
{
id: 2,
name: 'Learn CSS',
done: true
},
{
id: 3,
name: 'Learn JavaScript',
done: true
},
{
id: 4,
name: 'Learn Angular',
done: true
}
]
}
]

const hasFalseDone = notes.filter(note => note.todos.some(todo => todo.done === false))

/**

[[object Object] {
description: "Workout program",
id: 1,
todos: [[object Object] {
done: false,
id: 1,
name: "Push ups - 10 x 3"
}, [object Object] {
done: true,
id: 2,
name: "Abdominals - 20 x 3"
}, [object Object] {
done: true,
id: 3,
name: "Tapis Roulant - 15min"
}]
}]

**/
Julian Gonggrijp
@jgonggrijp
To be fair, with Underscore you can call it either any or some. And write things a bit more shortly.
_.filter(notes, note => _.some(note.todos, {done: false}))
// equivalent:
_.filter(notes, note => _.any(note.todos, {done: false}))
Marco Colia
@justoverclockl
can someone explain this in detail? so...what is the first parameter of notes.filter? and why the arrow?
and what is .some (i knnow that is a method) but what it return
Marco Colia
@justoverclockl
[
{
id: 1,
description: 'Workout program',
todos: [ [Object], [Object], [Object] ]
}
]
that is not the expected result @jgonggrijp
expected result must be:
{
id: 1,
description: 'Workout program',
todos: [
{
id: 1,
name: 'Push ups - 10 x 3',
done: false                                        //this contain a false flag...so this object need to be returned
},
{
id: 2,
name: 'Abdominals - 20 x 3',
done: true
},
{
id: 3,
name: 'Tapis Roulant - 15min',
done: true
}
]
}
Julian Gonggrijp
@jgonggrijp
@justoverclockl That's the same result, the items in the todos array have just been collapsed in your first quote.
19 replies
Stephen James
@sjames1958gm
My example was wrong as I was testing done === true, not done === false. Also, I forgot that for js it is "some" not "any".
Julian Gonggrijp
@jgonggrijp

can someone explain this in detail? so...what is the first parameter of notes.filter?

A function that returns a boolean. filter returns all elements of the array (or more generally, of the collection if you use _.filter) for which that function returns true.

and why the arrow?

That's basically a shorthand for an anonymous function. (a, b) => c means roughly (not exactly) the same as function(a, b) { return c; }.

Stephen James
@sjames1958gm
@gianfabiopezzolla That's what I get for using my memory :(
Julian Gonggrijp
@jgonggrijp

and what is .some (i knnow that is a method) but what it return

It returns a boolean: true if at least one element in the array/collection passes the test, false otherwise.

Marco Colia
@justoverclockl
guys, how do you override a method in an extended class? i have a class that returns a bank account deposit, in an extended class i want to return the same values plus 3% more if the deposit is >= 1000

class BankAccount {
#amount = 0;

constructor(initialAmount) {
this.#amount = initialAmount;
}

deposit(amount) {
this.#amount += amount;
}

withdraw(amount) {
this.#amount -= amount;
}

view() {
console.log(this.#amount);
}
}

class BankAccountVip extends BankAccount {                 //    i've started to create this
constructor(initialAmount, interest) {
super(initialAmount);
}
}

const bankAccountVip = new BankAccountVip(1000);
bankAccountVip.deposit(500);
bankAccountVip.deposit(1200);
bankAccountVip.withdraw(800);
bankAccountVip.deposit(3500);
bankAccountVip.view();          // this need to be returned with 3% of interests if the balance is >= 1000
Marco Colia
@justoverclockl
i need to override the deposit method maybe...but how
Stephen James
@sjames1958gm
Marco Colia
@justoverclockl
tried with something like

class BankAccountVip extends BankAccount {
constructor(initialAmount, interest) {
super(initialAmount);
this.interest = interest
}
deposit(amount) {
super.deposit(amount);
if (amount >= 1000) {
console.log(amount)
return amount + (amount *= 3 / 100)
}
}
}
but not work, the view(parent) does not add the percentage
Stephen James
@sjames1958gm
Your overriding deposit function is not updating the #amount variable
Maybe call super.deposit(amount); with the updated amount if >= 1000
Marco Colia
@justoverclockl
i'm trying with no success
Stephen James
@sjames1958gm
deposit(amount) {

if (amount >= 1000) {
console.log(amount)
amount += (amount * (3 / 100))
}
super.deposit(amount);
}
Marco Colia
@justoverclockl
damn.........3 hour to understand this
Stephen James
@sjames1958gm
It'll get better over time and then you'll spend 3 hours on some stupid typo, which you are just not seeing.
Marco Colia
@justoverclockl
:D
Marco Colia
@justoverclockl
what i need to be clear is if i can do try catch inside a class method, for example if i want to check if deposit is not a negative number