Skip to content

Instantly share code, notes, and snippets.

@aquaductape
Created May 22, 2020 20:06
Show Gist options
  • Save aquaductape/902f2bcffa5020fd728a50afe9d916d6 to your computer and use it in GitHub Desktop.
Save aquaductape/902f2bcffa5020fd728a50afe9d916d6 to your computer and use it in GitHub Desktop.
exercise to check if input is object without using Equality operators or Object.is()
// exercise to check if input is object without using
// Equality operators or Object.is()
const isObject = (input) => {
/******* Easiest Way ********/
if (!input) return false;
return !!(typeof input).match(/object|function/);
/******* Longer Solution ********/
if (!input) return false; // null or undefined
// We can check by adding property to the input.
// This works out since primitives are immutable
// adding properties to primitives silently do nothing
// prop happens to already exist in input
if (input.hasOwnProperty("prop")) {
return true;
}
input.prop = true;
if (input.prop) {
// input is successfully an object
// however the input now has an extra key
// our function must be pure and avoid side effects
// remove prop key
delete input.prop;
return true;
} else {
return false;
}
};
const objA = { whale: "🐋" };
const objB = { prop: "existing" };
const objC = {};
const arrA = ["🐋"];
const arrB = [];
const arrC = [];
arrB.prop = "existing";
console.log("hi", isObject("hi"));
console.log(true, isObject(true));
console.log(false, isObject(false));
console.log(null, isObject(null));
console.log(undefined, isObject(undefined));
console.log(NaN, isObject(NaN));
console.log(0, isObject(0));
console.log(5, isObject(5));
console.log(5n, isObject(5n));
console.log({}, isObject({}));
console.log([], isObject([]));
console.log(
function () {},
isObject(function () {})
);
console.log(objA, isObject(objA));
console.log(objB, isObject(objB));
console.log(objC, isObject(objC));
console.log(arrA, isObject(arrA));
console.log(arrB, isObject(arrB));
console.log(arrC, isObject(arrC));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment