Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
  • Dec 21 2018 17:11
    @MadLittleMods banned @OmarAlmaqtri
  • Jun 05 2018 23:13
    @MadLittleMods banned @LWSS
  • May 25 2018 16:50
    @MadLittleMods banned @TheRedstoneTaco
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
because if i do try catch inside deposit(amount) basically nothing happen...all run normally without any check
Marco Colia
@justoverclockl
this work

deposit(amount) {
    if (amount <= 0) {
      throw 'Error: value must be  > than 0'
    }
      this.#amount += amount;

  }
but not with try catch
Marco Colia
@justoverclockl
this work also
deposit(amount) {
    try {
      if (amount <= 0) {
        throw new Error('Error: value must be  > than 0')
      }
    }
    catch(err) {
      console.log(err.message)
    }
    finally {
      this.#amount += amount;
    }
  }
but if i do bankAccount.deposit(-1) i see the error but the deposit is executed
Marco Colia
@justoverclockl
maybe i need to remove finally...then it works
Marco Colia
@justoverclockl
i hope i found the correct way
Stephen James
@sjames1958gm

The try/catch will hide the exception from outside the function.
Code that throws and catches in the same location doesn't really make sense.

try {
   throw "x"
} catch "x" {
}

The finally block says after trying or catching do this, so that is not what you would want.

The first way seems correct and then you would have the try/catch where you are calling deposit
Marco Colia
@justoverclockl
guys there's a way to filter out only id and age entries from an object?

const person = {
  id: 1,
  firstName: 'john',
  lastName: 'doe',
  age: 25,
};

const json = JSON.stringify(person);

console.log(json); // Should return: { id: 1, age: 25 }

// output is: {"id":1,"firstName":"john","lastName":"doe","age":25}
Marco Colia
@justoverclockl
nevermind, i've figured it out const json = JSON.stringify(person,['id','age']);
Niko
@niko:chat.tgp.io
[m]
if you dont want to stringify it: const { id, age } = person; const filteredPerson = { id, age };
Julian Gonggrijp
@jgonggrijp
Or _.pick(person, ['id', 'age']).
Marco Colia
@justoverclockl
yeah, now that is clear, now the problem is the next exercise, object destructuring -.-
Stephen James
@sjames1958gm
What Niko did above is exactly that. With {} on the left of the = your are selecting fields from the object and assigning them to like named variables
Marco Colia
@justoverclockl
yes but what if i want to destructure the above person object and return a key: value using only spread/rest operator?
if i do: const { id, firstName, lastName, age } = person i get only value
so the output is 1 John Doe 25
what if i want output id:1 firstName: john lastName: Doe, age:25 using only destructuring?
Julian Gonggrijp
@jgonggrijp

@justoverclockl That takes two steps, as @niko:chat.tgp.io demonstrated. Alternatively, you can do this, but this is not destructuring:

const filteredPerson = {
    id: person.id,
    age: person.age,
};

Honestly, for the shortest possible expression, just use Underscore.

Lauro
@Lauro235

I'm trying to remove every other occurrence of a word from an array. I have made an indexArray, which lists index numbers of a given word as it appears. I was hoping to use this to create a filter on the original array.

let story =
  'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let storyWords = story.split(" ");

function listIndex(arr, val) {
  const indexArray = [];
  let idx = arr.indexOf(val);
  while (idx != -1) {
    indexArray.push(idx);
    idx = arr.indexOf(val, idx + 1);
  }
  console.log(indexArray);
  // You have an array. Measure length, at every even index number store the value (the initial index of the word)
  for(let i = 0; i < indexArray.length; i++) {
    if(i % 2 === 1){
      console.log(indexArray[i])
    }
  }
}

listIndex(storyWords, "really");

This is the path I'm on currently, but could be barking up the wrong tree. Please could you give me tips on a good way forward?

Julian Gonggrijp
@jgonggrijp

@Lauro235 I expect that your listIndex function will correctly produce all indices of the given word. I would suggest calling it listIndices because it returns multiple indices.

If you want to remove words from the storyWords array by index, the way forward is to go... backwards. :-) By removing the last word first, you ensure that the indices of all words before it stay the same.

For fun and education, here is a functional way to write listIndices using Underscore:

const equalTo = expected => actual => actual === expected;

function listIndices(array, word) {
    return _.chain(array)
    .pairs()
    .groupBy(_.compose(equalTo(word), _.property('1')))
    .get('true')
    .map('0')
    .value();
}
Lauro
@Lauro235

Good point on the naming of the function. I haven't seen this chaining of methods that often (starting from a new line each time), but this is fine because Javascript doesn't recognise white space in this instance?

Looking forward to googling these methods and figuring out what you did :P

Lauro
@Lauro235

This language is confusing me....

"The this keyword references the calling object which provides access to the calling object’s properties. In the example above, the calling object is goat and by using this we’re accessing the goat object itself, and then the dietType property of goat by using property dot notation".

It's taken from a lesson about the this keyword as it relates to an object. https://www.codecademy.com/courses/introduction-to-javascript/lessons/advanced-objects/exercises/adv-this

const goat = {
  dietType: "herbivore",
  makeSound() {
    console.log("baaa");
  },
  diet() {
    console.log(this.dietType); //REVIEW
  },
};

goat.diet()

My point of confusion is on what the calling object is. Do they mean goat.diet() or do they just mean the object it self const goat?

Stephen James
@sjames1958gm
They mean goat itself.
goat.diet() is calling the function diet on the object goat.
Lauro
@Lauro235
Thanks Stephen! :D
Julian Gonggrijp
@jgonggrijp

@Lauro235

Good point on the naming of the function. I haven't seen this chaining of methods that often (starting from a new line each time), but this is fine because Javascript doesn't recognise white space in this instance?

Right. In principle, statements are terminated by semicolons. Sometimes when you write a linebreak without a semicolon, the JS interpreter is still able to figure out that you meant to terminate the statement, but in principle, line breaks do not have a meaning in JavaScript. In fact, neither does indentation. We say that whitespace is insignificant in JS.

Marco Colia
@justoverclockl
hello again guys, i have a question, is it safe to make a fetch request with {cache: "force-cache"}? this "cache" will be refreshed if there are new data?
Marco Colia
@justoverclockl
@jgonggrijp
Julian Gonggrijp
@jgonggrijp
@justoverclockl You can find that type of information well through the search function of the MDN web docs at https://developer.mozilla.org/.

I entered "fetch" there and ended up at https://developer.mozilla.org/en-US/docs/Web/API/fetch. On that page, it says:

cache
A string indicating how the request will interact with the browser's HTTP cache. The possible values, default, no-store, reload, no-cache, force-cache, and only-if-cached, are documented in the article for the cache property of the Request object.

So the article about the cache property is probably what you need.
PakDragoon
@PakDragoon
I am working on react project. I am recording a video with react-media-recorder package. Now i want to store the recorded video direcrly into the mongodb. Does anyone have knowledge about where that video blob is getting stored?
mounikesh42
@mounikesh42
guys can we use javascript to open a popup page and get info back to the parent page
not just basically on javascript but using any frameworks like angular or react ???
Julian Gonggrijp
@jgonggrijp
@mounikesh42 Probably, though it depends a bit on what you mean by "popup page".
Also, if you can do it with plain JavaScript, you can also do it with JavaScript plus libraries like Angular or React.
mounikesh42
@mounikesh42
@jgonggrijp so basically parent page triggers a third party page in popup
after it loads it generates a token in the popup page url
now i wanna grab that url into the parent page
is that possible ???
i can open popups using javascript or anyother frameworks but having one way connection from parent page to popup page is what i wanted
not sure if it works