uint32 arrayLike type guards

by Artem

JavaScript

'use strict';

const guard = {
	guard(x) {
  	if (!this.test(x)) {
    	throw new TypeError(this + ' was expected');
    }
  },
  or(other) {
  	const result = Object.create(guard);
    const self = this;
    result.test = function(x) {
    	return self.test(x) || other.test(x);
    };
    const description = self.toString() + ' or ' + other.toString();
    result.toString = function() {
    	return description;
    }
    return result;
  }
};

const uint32 = Object.create(guard);
uint32.test = function(x) {
	return typeof x === 'number' && x === (x >>> 0);
};
uint32.toString = function() {
	return 'uint32';
};

const arrayLike = Object.create(guard);
arrayLike.test = function(x) {
	return typeof x === 'object' && x && uint32.test(x.length);
};
arrayLike.toString = function() {
	return 'array-like object';
};

function BitVector() {}
BitVector.prototype.enableBit = function(x) {};
BitVector.prototype.enable = function(x) {
	uint32.or(arrayLike).guard(x);
	if (typeof x === 'number') {
		this.enableBit(x);
  } else {
  	for (let i = 0, n = x.length; i < n; i++) {
    	this.enableBit(x[i]);
    }
  }
};

const bits = new BitVector();
bits.enable(4);
bits.enable([1, 3, 8, 17]);
bits.enable('789');