1

I'm wanting to create a function that will check if an array's object matches a type array.

An example of what I'm trying to achieve is

let syntax = [Number, String];
let arguments = [23, 'some string', {some: 'ignored argument'}];

// How would I check if syntax[0] matches arguments[0] without hardcoding
// it to keep it flexible?

I want to be able to have some sort of function that'll basically check if arguments[0] matches the type on syntax[0], while also having it to be able to check more than just one, or two, and so on types (no hardcoding if (something[0] === somethingAgain[0])), however I have no idea how to even achieve this.

Sorry if this is a loaded question! I'm fine with using third-party modules via NPM if this is a long shot.

Rek
  • 139
  • 11
  • Does it have to be `Number` and `String`? `number` and `string` (types, not constructors) would be easier to achieve with `typeof` – georg Jun 09 '19 at 02:40
  • @georg No, i'd want it to at least work with an object type too, however it looks like the answer below by jack seems to work with that as well. – Rek Jun 09 '19 at 03:09
  • See [*Get the name of an object's type*](https://stackoverflow.com/questions/332422/get-the-name-of-an-objects-type) for a discussion about types and how to distinguish them. Using *typeof* is likely more efficient than calling a constructor, other approaches are more flexible (e.g. distinguish between functions and plain objects, NaN and number, null, etc.). – RobG Jun 09 '19 at 03:16

1 Answers1

0

Use every:

let syntax = [Number, String];
let arguments = [23, 'some string', {some: 'ignored argument'}];
let matches = syntax.every((f, i) => f(arguments[i]) === arguments[i]);
console.log(matches);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • 1
    Nope, counter-example: `[String] and [23]`. To fix that, get rid of `new` and use `===`, not `==` – georg Jun 09 '19 at 02:38
  • 1
    Code–only answers aren't that helpful. I this case, there are many details to explain. Number and String aren't Types, they're constructors and this just works as a quirk of calling those constructors. How to test for other Types like *undefined* and *null*? It also fails for NaN, which is Type Number. – RobG Jun 09 '19 at 02:57
  • No worries @RekkisomoHarley, always glad to help. – Jack Bashford Jun 09 '19 at 03:05
  • Oh, also fails for Symbol. ;-) – RobG Jun 09 '19 at 03:20