Skip to content

Instantly share code, notes, and snippets.

@fwg
Forked from line-o/testIsArrayOf.js
Created February 1, 2012 17:55
Show Gist options
  • Save fwg/1718323 to your computer and use it in GitHub Desktop.
Save fwg/1718323 to your computer and use it in GitHub Desktop.
isArrayOf(array2test, type2match)
var typeUtils =
literals = ['boolean', 'string', 'number', 'object'],
types2test = literals.concat([new RegExp(/asd/), new Number(1), new String('#')]),
testArrays = [
[true, false, true],
[1, 2, 3],
['a', 'b', 'c'],
[/sdf/, /asdf/, /asf/],
[{}, {}, {}],
[new String('a'), new String('b'), new String('c')],
[new Number(1), new Number(2), new Number(3)]
],
results = [];
function testIsArrayOf (array, types) {
return {
'tested':array.toString(),
'results':types.map(function(type, idx) {
return isArrayOf(array, type)})}
}
function renderResults (results, types) {
var sep = ' | ',
maxL = results.reduce(function (prev, curr, idx, array) {
var len = curr.tested.toString().length
return ((prev > len) ? prev : len)}),
rows = [renderTHead(types)]
function pad (str, len) {
var ret = str, pad = len - str.length
for (i = pad - 1; i >= 0; i--) ret += ' '
return ret
}
function renderTHead (cols) {
return [pad('title', maxL)].concat(cols).join(sep)
}
function renderResHead (tested) {
var pad = maxL - tested.length,
rowHead = tested, i
for (i = pad - 1; i >= 0; i--) rowHead += ' '
return rowHead
}
function renderResult (el) {
var rowParts = [renderResHead(el.tested)],
rowRes = el.results.map(function ( el) {
return (el === 1 ? 'x':' ')})
return rowParts.concat(rowRes).join(sep)
}
return rows.concat(results.map(renderResult))
}
//run tests
results = testArrays.map(function (arr){
return testIsArrayOf(arr, types2test)})
console.log(renderResults(results, types2test))
//module.exports = isArrayOf;
function extractConstructorName (o) {
var s = o.constructor.toString()
return s.substring(9, s.indexOf('(')) //'function '...'('
}
function isArrayOf (array, type) {
var reduce, test
constructorMatch = extractConstructorName(type)
//compile testing functions
function testLiteral (o) {
return (typeof o == type)}
function testPrototype (o) {
return (extractConstructorName(o) == constructorMatch)}
//choose testing function and run test
test = (literals.indexOf(type) >= 0) ? testLiteral : testPrototype
return array.reduce(function (prev, curr, idx, array) {
return (prev & test(curr))}, true)
}
module.exports = typeUtils = {
isArrayOf = isArrayOf,
extractConstructorName = extractConstructorName
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment