Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exercise 5 in chapter 4 #6

Open
ghost opened this issue Apr 23, 2020 · 3 comments
Open

exercise 5 in chapter 4 #6

ghost opened this issue Apr 23, 2020 · 3 comments
Labels
question Further information is requested

Comments

@ghost
Copy link

ghost commented Apr 23, 2020

I think that this assertion function is comparing the array 'a' with the each elements of array 'b'.
So, I tried that the arguments [1], [1], [1] give to function is. The result was false.
I think that the result is true in this case.
Please tell me why this assertion function 'is' is correct?
I read this book in Japanese. If the translation is not good, could you tell me the sentences of the exercise 5 in English?
スクリーンショット 2020-04-24 2 18 29

@bcherny
Copy link
Owner

bcherny commented May 2, 2020

Hey there! This example may be a little confusing -- is performs a shallow comparison, but the example might make it seem like we actually want a deep comparison.

This should work, since we're checking that each argument references the same value (it does):

let array = [1, 2]
console.log(is(array, array, array)) // true

This wouldn't work, because each array we pass in is a brand new reference:

console.log(is([1, 2], [1, 2], [1, 2])) // false

You could, of course, extend is to perform a deep comparison (let's call it looksLike). Want to try implementing it? Once you're done, it should work like this:

looksLike('a', 'a', 'a') // true
looksLike([1, [2]], [1, [2]], [1, [2]], [1, [2]]) // true
looksLike([1], [1], [2]) // false

@bcherny bcherny assigned ghost May 2, 2020
@bcherny bcherny added the question Further information is requested label May 2, 2020
@alexovn
Copy link

alexovn commented Sep 16, 2023

You just need to make something like this:

function is<T>(a: T, ...b: [T, ...T[]]): boolean {
  return b.every((_) => JSON.stringify(_) === JSON.stringify(a));
}

@alexovn
Copy link

alexovn commented Sep 16, 2023

More verbose variant:

function is<T>(
  a: T,
  ...b: [T, ...T[]]
): boolean {
  let c
  for(let i = 0; i < b.length; i++) {
    c = JSON.stringify(a) === JSON.stringify(b[i])
    return c
  }
  return c !== undefined ? c : false
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants