The function checks whether an array is of a specific type (only contains elements of that type), the types the function accepts for checking is basically all the JavaScript types plus any types that the user may define manually (using a constructor).
What would you do to make the function more sophisticated ? What would you remove or add ? How would you improve or extend the function ?
const checkArrayType = function checkArrayType(arr, type) { if (!Array.isArray(arr)) { throw new Error('The argument "arr" must be an array!'); } else if (type !== null && type !== undefined && typeof type != 'function') { throw new Error('The argument "type" must be a function, "null", or "undefined"!'); } // 'null' and 'undefined' require a different check than the main one if (type === null || type === undefined) { return arr.every(function(e){ return e === type; }); } return arr.every(function(e){ /* * not using 'instanceof' because it would return 'true' * for cases like 'subObj instanceof Object'. * --------------------------------- * using 'Object(e)' so that the check works for primitives, see: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object */ return Object.getPrototypeOf(Object(e)) === type.prototype; }); }; console.log(checkArrayType([1,2,3,4], Number)); // true console.log(checkArrayType(['hello', 10], String)); // false console.log(checkArrayType([[1, 2.5], ['a', 'b']], Array)); // true console.log(checkArrayType([null, null, null, null], null)); // true console.log(checkArrayType([new String('hello'), new String('world')], Object)); // false var Foo = function Foo(){}; console.log(checkArrayType([new Foo(), new Foo()], Foo)); // true console.log(checkArrayType({a: null}, null)); // throws error console.log(checkArrayType([], 'abc')); // throws error
One more thing, how am I supposed to deal with long comments like the one in this snippet ?