urbit-ob

JavaScript utilities for phonemic base wrangling.
Log | Files | Refs | README

commit 2a60d7f9b51e805454065c95aa34094ed5359e29
parent f3ce19a94bfd03afd372d271d24bf28bbbb8f5cf
Author: Jared Tobin <jared@jtobin.io>
Date:   Fri,  5 Oct 2018 13:25:23 +1300

Add @q encoding.

See urbit/arvo#824.

Diffstat:
Msrc/index.js | 23++++++++++++++++++++++-
Mtest/core.test.js | 24++++++++++++++++++++++++
2 files changed, 46 insertions(+), 1 deletion(-)

diff --git a/src/index.js b/src/index.js @@ -3,7 +3,8 @@ */ const bnjs = require('bn.js') -const { reduce, isUndefined, isString, every, map } = require('lodash') +const { reduce, concat, chunk, isUndefined, + isString, every, map } = require('lodash') const raku = [ 3077398253, @@ -356,6 +357,25 @@ const patp = (n) => { : loop(sxz, zero, '')) } +// bignum patq +const patq = (n) => { + const buff = n.toArrayLike(Buffer) + + const chunked = + buff.length % 2 === 1 && buff.length !== 1 + ? concat([[buff[0]]], chunk(buff.slice(1), 2)) + : chunk(buff, 2) + + const name = byts => + isUndefined(byts[1]) + ? getSuffix(byts[0]) + : getPrefix(byts[0]) + getSuffix(byts[1]) + + return chunked.reduce((acc, elem) => + acc + (acc === '~' ? '' : '-') + name(elem), '~') +} + + // returns the class of a ship from it's name const tierOfpatp = name => { const l = len(patp2arr(name)) @@ -500,6 +520,7 @@ module.exports = { isValidName: isValidName, patp: patp, + patq: patq, _add2patp: _add2patp, _getsuffix: getSuffix, diff --git a/test/core.test.js b/test/core.test.js @@ -130,3 +130,27 @@ test('correctly encodes a big hex string as @p', () => { let expected = '~divmes-davset-holdet--sallun-salpel-taswet-holtex--watmeb-tarlun-picdet-magmes--holter-dacruc-timdet-divtud--holwet-maldut-padpel-sivtud'; expect(ob.patp(input)).toBe(expected); }); + +test('correctly encode 0 as @q', () => { + let input = new bnjs('0'); + let expected = '~zod'; + expect(ob.patq(input)).toBe(expected); +}); + +test('correctly encode 0x102 as @q', () => { + let input = new bnjs('0102', 'hex'); + let expected = '~marbud'; + expect(ob.patq(input)).toBe(expected); +}); + +test('correctly encode 0x10102 as @q', () => { + let input = new bnjs('010102', 'hex'); + let expected = '~nec-marbud'; + expect(ob.patq(input)).toBe(expected); +}); + +test('correctly encode 0x1010101010101010102 as @q', () => { + let input = new bnjs('01010101010101010102', 'hex'); + let expected = '~marnec-marnec-marnec-marnec-marbud'; + expect(ob.patq(input)).toBe(expected); +});