UNPKG

dareway-rui

Version:

91 lines (71 loc) 2.5 kB
'use strict'; var _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault'); Object.defineProperty(exports, '__esModule', { value: true }); exports.filterValueByMaxLength = filterValueByMaxLength; exports.default = void 0; var _typeof2 = _interopRequireDefault(require('@babel/runtime/helpers/typeof')); function getByteVal(val, max) { var returnValue = '', byteValLen = 0; for (var i = 0; i < val.length; i++) { var charCode = val.charCodeAt(i); if (charCode >= 0 && charCode <= 128) { byteValLen += 1; } else { byteValLen += 2; } if (byteValLen > max) break; returnValue += val.charAt(i); } return returnValue; } function getBinaryLength(str) { if (typeof str == null) { throw new Error('getBinaryLength(str) 入参 str 为 null,请检查!'); } var binaryLength = 0; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) { binaryLength += 1; } else { binaryLength += 2; } } return binaryLength; } function filterValueByMaxLength(value) { var maxLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1; if (!(typeof maxLength === 'number' && (maxLength > 0 || maxLength === -1))) { throw new Error( 'maxLength \u5FC5\u987B\u4E3A number \u7C7B\u578B\uFF0C\u4E14\u53D6\u503C\u53EA\u80FD\u662F \u3010-1 \u6216 >0 \u3011\uFF0C\u5F53\u524D\u4F20\u5165\u3010' .concat(maxLength, '\uFF0C') .concat((0, _typeof2.default)(maxLength), '\u3011\uFF0C\u8BF7\u68C0\u67E5\uFF01') ); } if (maxLength === -1) { return value; } else if (maxLength > 0) { var newValue = value; var cLength = getBinaryLength(value); if (cLength > maxLength) { newValue = getByteVal(value, maxLength); } return newValue; } else { throw new Error( 'filterValueByMaxLength(value, maxLength) \u5165\u53C2 maxLength \u503C\u4E3A\u3010'.concat( maxLength, '\u3011\uFF0C\u6B63\u786E\u53D6\u503C\u4E3A\u3010-1 \u6216 >0\u3011\uFF0C\u8BF7\u68C0\u67E5\uFF01' ) ); } } var _default = { getByteVal: getByteVal, getBinaryLength: getBinaryLength }; exports.default = _default; //@ sourceMappingURL=util.js.map