git ssb

0+

wanderer🌟 / js-primea-objects



Tree: 94b5daa6362ac3c9f4a4c781894a73ad2c5160c5

Files: 94b5daa6362ac3c9f4a4c781894a73ad2c5160c5 / utils.js

1181 bytesRaw
1const { FunctionRef, ModuleRef, generateActorId, getType } = require('./')
2
3const actorRefToId = ref => ref.reduce((parent, curr) => generateActorId({ parent, nonce: curr }), null)
4
5const toHex = arg => Buffer.isBuffer(arg) ? `0x${arg.toString('hex')}` : arg
6
7const fromHex = arg => typeof arg !== 'string' ? arg : Buffer.from(arg.slice(0, 2) === '0x' ? arg.slice(2) : arg, 'hex')
8
9const toJSON = (arg, includeOptional = true) => {
10 switch (getType(arg)) {
11 case 'elem':
12 return arg.map(a => toJSON(a, includeOptional))
13 case 'id':
14 case 'func':
15 case 'mod':
16 return arg.toJSON(includeOptional)
17 case 'link':
18 return {
19 '@Link': {
20 '/': toJSON(arg['/'], includeOptional)
21 }
22 }
23 case 'data':
24 default:
25 return toHex(arg)
26 }
27}
28
29const fromJSON = arg => {
30 if (typeof arg === 'object') {
31 if (Array.isArray(arg)) {
32 return arg.map(fromJSON)
33 }
34
35 if (arg['@FunctionRef']) {
36 return FunctionRef.fromJSON(arg)
37 } else if (arg['@ModuleRef']) {
38 return ModuleRef.fromJSON(arg)
39 }
40 }
41
42 return fromHex(arg)
43}
44
45module.exports = {
46 actorRefToId,
47 toJSON,
48 fromJSON,
49 toHex,
50 fromHex
51}
52

Built with git-ssb-web