From 718f83bfaf56cb4c7cdda7ab3c9ed2c06177631a Mon Sep 17 00:00:00 2001 From: Kirill Fomichev Date: Thu, 22 Sep 2016 10:49:04 +0300 Subject: [PATCH] Add byteLength --- README.md | 5 +++-- lib/b64.js | 17 +++++++++++++---- test/convert.js | 3 ++- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ed31d1a..e546d86 100644 --- a/README.md +++ b/README.md @@ -21,11 +21,12 @@ With [npm](https://npmjs.org) do: `var base64 = require('base64-js')` -`base64` has two exposed functions, `toByteArray` and `fromByteArray`, which both take a single argument. +`base64` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. +* `byteLength` - Takes a base64 string and returns length of byte array * `toByteArray` - Takes a base64 string and returns a byte array * `fromByteArray` - Takes a byte array and returns a base64 string ## license -MIT \ No newline at end of file +MIT diff --git a/lib/b64.js b/lib/b64.js index 4b7c478..44e5d99 100644 --- a/lib/b64.js +++ b/lib/b64.js @@ -1,5 +1,6 @@ 'use strict' +exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray @@ -20,10 +21,8 @@ function init () { init() -function toByteArray (b64) { - var i, j, l, tmp, placeHolders, arr +function placeHoldersCount (b64) { var len = b64.length - if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } @@ -33,9 +32,19 @@ function toByteArray (b64) { // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} +function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data + return b64.length * 3 / 4 - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars diff --git a/test/convert.js b/test/convert.js index ff275b2..19a6665 100644 --- a/test/convert.js +++ b/test/convert.js @@ -13,7 +13,7 @@ var checks = [ ] test('convert to base64 and back', function (t) { - t.plan(checks.length) + t.plan(checks.length * 2) for (var i = 0; i < checks.length; i++) { var check = checks[i] @@ -25,6 +25,7 @@ test('convert to base64 and back', function (t) { str = map(arr, function (byte) { return String.fromCharCode(byte) }).join('') t.equal(check, str, 'Checked ' + check) + t.equal(b64.byteLength(b64Str), arr.length, 'Checked length for ' + check) } })