`is` implementation can not pass leetcode testing
kayac-chang opened this issue · comments
For
Line 28 in 7ed79b4
Although leet code is not a real-world scenario,
but I think is good to have an implementation to pass this exam.
The re-implementation below can pass leet code exam, maybe we can consider using this:
function is(Ctor, val) {
if(val === null || val === undefined || typeof Ctor !== 'function') return false;
return Object(val) instanceof Ctor;
}
another implementation is following the prototype chain
function is(Ctor, val) {
if (val === null || val === undefined) {
return false
}
if (val.constructor === Ctor){
return true
}
return is(Ctor, Object.getPrototypeOf(val))
}
I don't have a strong opinion here, but a PR would be good to see along with if there are any changes in which tests pass/fail, and what new tests would pass with the change.
Both of these implementations don't work as I would expect it. Both of them would fail one of the existing examples:
is(Object, 's') // returns true, but should be false
Both of these implementations don't work as I would expect it. Both of them would fail one of the existing examples:
is(Object, 's') // returns true, but should be false
Hey @jlissner,
this is also the weird part of me, I couldn't fully understand.
In leetcode exam, they actually consider 's'
is an Object instance,
but in ramda we consider 's' is not an Object instance.
I just wonder which is the standard way to understand about this.
Let's say I have a variable named maybeJson
, and I know that maybeJson
could either be a string
or an object
, like a stringified JSON or an already parsed JSON, I might write something like
const definitelyAnObject = R.when(R.is(String), JSON.parse)(maybeJson);
// or
const definitelyAnObject = R.unless(R.is(Object), JSON.parse)(maybeJson);
and I'd expect them both to work. If is(Object, 's')
returns true
, then my code isn't going to work as expected.
All this to say, I believe that is(Object, 's')
SHOULD return false
.
Let's say I have a variable named
maybeJson
, and I know thatmaybeJson
could either be astring
or anobject
, like a stringified JSON or an already parsed JSON, I might write something likeconst definitelyAnObject = R.when(R.is(String), JSON.parse)(maybeJson); // or const definitelyAnObject = R.unless(R.is(Object), JSON.parse)(maybeJson);and I'd expect them both to work. If
is(Object, 's')
returnstrue
, then my code isn't going to work as expected.All this to say, I believe that
is(Object, 's')
SHOULD returnfalse
.
Yes, the use case also make sense for me.
I think leetcode exam is not very satisfy the real world use case.
Close this issue here.
See also, https://fr.umio.us/the-philosophy-of-ramda/#somewhatsurprising for a discussion of this.
Also, I would like to point out that ECMAScript makes a distinction between a few literal values vs their object form, and 's'
is a string literal, not a string object.