array.js 860 B

123456789101112131415161718192021222324
  1. // This is Array extended to have .toString(['utf8'|'hex'|'base64'])
  2. function SeaArray() {}
  3. Object.assign(SeaArray, { from: Array.from })
  4. SeaArray.prototype = Object.create(Array.prototype)
  5. SeaArray.prototype.toString = function(enc, start, end) { enc = enc || 'utf8'; start = start || 0;
  6. const length = this.length
  7. if (enc === 'hex') {
  8. const buf = new Uint8Array(this)
  9. return [ ...Array(((end && (end + 1)) || length) - start).keys()]
  10. .map((i) => buf[ i + start ].toString(16).padStart(2, '0')).join('')
  11. }
  12. if (enc === 'utf8') {
  13. return Array.from(
  14. { length: (end || length) - start },
  15. (_, i) => String.fromCharCode(this[ i + start])
  16. ).join('')
  17. }
  18. if (enc === 'base64') {
  19. return btoa(this)
  20. }
  21. }
  22. module.exports = SeaArray;