feat: use str.repeat for padding (fixes #4)

feat: add str.repeat polyfill for older browsers

feat: add module field to package.json
This commit is contained in:
pimlie 2018-10-19 10:03:20 +02:00
parent e1e33f9cb6
commit 860f1ed9e6
4 changed files with 41 additions and 8 deletions

@ -10,6 +10,7 @@ var PRINTJ/*:PRINTJModule*/ = /*::(*/{}/*:: :any)*/;
export const version = PRINTJ.version;
#else
var PRINTJ/*:PRINTJModule*/;
#include "05_polyfill.js"
(function (factory/*:(a:any)=>void*/)/*:void*/ {
/*jshint ignore:start */
/*eslint-disable */

38
bits/05_polyfill.js Normal file

@ -0,0 +1,38 @@
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
if (!String.prototype.repeat) {
String.prototype.repeat = function(count) {
'use strict';
if (this == null) {
throw new TypeError('can\'t convert ' + this + ' to object');
}
var str = '' + this;
count = +count;
if (count != count) {
count = 0;
}
if (count < 0) {
throw new RangeError('repeat count must be non-negative');
}
if (count == Infinity) {
throw new RangeError('repeat count must be less than infinity');
}
count = Math.floor(count);
if (str.length == 0 || count == 0) {
return '';
}
// Ensuring count is a 31-bit integer allows us to heavily optimize the
// main part. But anyway, most current (August 2014) browsers can't handle
// strings 1 << 28 chars or longer, so:
if (str.length * count >= 1 << 28) {
throw new RangeError('repeat count must not overflow maximum string size');
}
var maxCount = str.length * count;
count = Math.floor(Math.log(count) / Math.log(2));
while (count) {
str += str;
count--;
}
str += str.substring(0, maxCount - str.length);
return str;
}
}

@ -1,12 +1,5 @@
#define isnan isNaN
//#define PAD_(x,c) (x >= 0 ? new Array(((x)|0) + 1).join((c)) : "")
var padstr/*:{[s:string]:string}*/ = {
" ": " ",
"0": "000000000000000000000000000000000",
"7": "777777777777777777777777777777777",
"f": "fffffffffffffffffffffffffffffffff"
};
#define PAD_(x,c) (x >= 0 ? padstr[c].substr(0,x) : "")
#define PAD_(x,c) (x >= 0 ? c.repeat(x) : "")
#ifdef DO_NOT_INLINE
function pads(x/*:number*/, c/*:string*/)/*:string*/ { return PAD_(x,c); }
#define PADS(x,c) pads(x,c)

@ -13,6 +13,7 @@
"printj": "./bin/printj.njs"
},
"main": "./printj",
"module": "./print.mjs",
"types": "types",
"browser": {
"process": false,