DEV Community

loading...

Can you hack this? #1

alfredosalzillo profile image Alfredo Salzillo 🐺 ・1 min read

Say that we have a function called nameEqualsToItself how accept a person object as input that checks if the name property of the input object equal the same name property of the input object implemented like this:

const nameEqualsToItself = (person) => person.name === person.name
Enter fullscreen mode Exit fullscreen mode

Can you find the input that makes nameEqualsToItself return false?

const personX = ???
console.log(nameEqualsToItself(personX)) // print `false`
Enter fullscreen mode Exit fullscreen mode

Discussion (12)

pic
Editor guide
Collapse
afif profile image
Temani Afif • Edited
const personX={};
personX.name=NaN;
Enter fullscreen mode Exit fullscreen mode

OR simply

const personX={name:NaN};
Enter fullscreen mode Exit fullscreen mode

a. If x or y are any of NaN, +βˆžπ”½, or -βˆžπ”½, return false. ref

Collapse
akashkava profile image
Akash Kava

It will return false only for NaN, because Number.POSITIVE_INFINITY === Number.POSITIVE_INFINITY returns true, and it is same for negative infinity as well.

Collapse
alfredosalzillo profile image
Alfredo Salzillo 🐺 Author

Also if using a Getter or a Proxy returning different values each time :)

Thread Thread
atulcodex profile image
Atul Prajapati

You don't know everything πŸ˜›

Collapse
kinzmak profile image
Kins • Edited
const personX = { get name() { return Math.random() } };
console.log(nameEqualsToItself(personX)); //This will return false as well 
Enter fullscreen mode Exit fullscreen mode
Collapse
shane profile image
shane • Edited

This is big brain, love it

Collapse
aminnairi profile image
Amin

Using a Proxy.

"use strict";

const personNameEqualsItself = person => person.name === person.name;

const person = (() => {
  let boolean = true;

  return new Proxy({}, {get: (target, property) => property === "name" ? boolean = !boolean : undefined});
})();

console.log(personNameEqualsItself(person)); // false
console.log(personNameEqualsItself(person)); // false
console.log(personNameEqualsItself(person)); // false
Enter fullscreen mode Exit fullscreen mode
Collapse
rkichenama profile image
Richard Kichenama
const personX = new Proxy({}, { get (target, attr) { return /name/i.test(attr) ? Symbol('name') : target[attr]; });
Enter fullscreen mode Exit fullscreen mode
Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
alfredosalzillo profile image
Alfredo Salzillo 🐺 Author

It print true :) try it

Collapse
leviathanprogramming profile image
π‹π„π‘½πˆπ‘¨π“π‡π€π Programming

It printed false.

const nameEqualsToItself = (person) => person.name === person.name
const personX = { name: NaN, };
console.log(nameEqualsToItself(personX))
Enter fullscreen mode Exit fullscreen mode
Collapse
chakudi profile image
Vaishali JS

NaN is never equal to itself πŸ‘