quixote
Version:
CSS unit and integration testing
111 lines (87 loc) • 2.94 kB
JavaScript
// Copyright (c) 2014-2016 Titanium I.T. LLC. All rights reserved. For license, see "README" or "LICENSE" file.
"use strict";
var ensure = require("../util/ensure.js");
var Value = require("./value.js");
var Me = module.exports = function Pixels(amount) {
ensure.signature(arguments, [ [ Number, null ] ]);
this._none = (amount === null);
this._amount = amount;
};
Value.extend(Me);
Me.create = function create(amount) {
return new Me(amount);
};
Me.createNone = function createNone() {
return new Me(null);
};
Me.ZERO = Me.create(0);
Me.NONE = Me.createNone();
Me.prototype.compatibility = function compatibility() {
return [ Me ];
};
Me.prototype.isNone = function() {
ensure.signature(arguments, []);
return this._none;
};
Me.prototype.plus = Value.safe(function plus(operand) {
if (this._none || operand._none) return Me.createNone();
return new Me(this._amount + operand._amount);
});
Me.prototype.minus = Value.safe(function minus(operand) {
if (this._none || operand._none) return Me.createNone();
return new Me(this._amount - operand._amount);
});
Me.prototype.difference = Value.safe(function difference(operand) {
if (this._none || operand._none) return Me.createNone();
return new Me(Math.abs(this._amount - operand._amount));
});
Me.prototype.times = function times(operand) {
ensure.signature(arguments, [ Number ]);
if (this._none) return Me.createNone();
return new Me(this._amount * operand);
};
Me.prototype.average = Value.safe(function average(operand) {
if (this._none || operand._none) return Me.createNone();
return new Me((this._amount + operand._amount) / 2);
});
Me.prototype.compare = Value.safe(function compare(operand) {
var bothHavePixels = !this._none && !operand._none;
var neitherHavePixels = this._none && operand._none;
var onlyLeftHasPixels = !this._none && operand._none;
if (bothHavePixels) {
var difference = this._amount - operand._amount;
if (Math.abs(difference) <= 0.5) return 0;
else return difference;
}
else if (neitherHavePixels) {
return 0;
}
else if (onlyLeftHasPixels) {
return 1;
}
else {
return -1;
}
});
Me.min = function(l, r) {
ensure.signature(arguments, [ Me, Me ]);
if (l._none || r._none) return Me.createNone();
return l.compare(r) <= 0 ? l : r;
};
Me.max = function(l, r) {
ensure.signature(arguments, [ Me, Me ]);
if (l._none || r._none) return Me.createNone();
return l.compare(r) >= 0 ? l : r;
};
Me.prototype.diff = Value.safe(function diff(expected) {
if (this.compare(expected) === 0) return "";
if (this._none || expected._none) return "non-measurable";
var difference = Math.abs(this._amount - expected._amount);
var desc = difference;
if (difference * 100 !== Math.floor(difference * 100)) desc = "about " + difference.toFixed(2);
return desc + "px";
});
Me.prototype.toString = function toString() {
ensure.signature(arguments, []);
return this._none ? "no pixels" : this._amount + "px";
};