github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-supply-chain-master/fish_client/src/services/parsing.js (about) 1 /** 2 * Copyright 2017 Intel Corporation 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * ---------------------------------------------------------------------------- 16 */ 17 'use strict' 18 19 const _ = require('lodash') 20 const moment = require('moment') 21 const { FLOAT_PRECISION } = require('./payloads') 22 23 const STRINGIFIERS = { 24 LOCATION: v => `${v.latitude}, ${v.longitude}`, 25 tilt: v => `X: ${v.x}, Y: ${v.y}`, 26 shock: v => `Accel: ${v.accel}, Duration: ${v.duration}`, 27 '*': v => JSON.stringify(v, null, 1).replace(/[{}"]/g, '') 28 } 29 30 /** 31 * Parses a property value by its name or type, returning a string for display 32 */ 33 const stringifyValue = (value, type, name) => { 34 if (STRINGIFIERS[type]) { 35 return STRINGIFIERS[type](value) 36 } 37 if (STRINGIFIERS[name]) { 38 return STRINGIFIERS[name](value) 39 } 40 return STRINGIFIERS['*'](value) 41 } 42 43 /** 44 * Simple functions that turn numbers or number-like strings to 45 * an integer (in millionths) or back to a float. 46 */ 47 const toFloat = num => parseInt(num) / FLOAT_PRECISION 48 const toInt = num => parseInt(parseFloat(num) * FLOAT_PRECISION) 49 50 /** 51 * Calls toFloat on a property value, or it's sub-values in the case of 52 * location, tilt, or shock 53 */ 54 const floatifyValue = value => { 55 if (_.isString(value)) value = JSON.parse(value) 56 if (_.isObject(value)) return _.mapValues(value, toFloat) 57 return toFloat(value) 58 } 59 60 /** 61 * Parses seconds into a date/time string 62 */ 63 const formatTimestamp = sec => { 64 if (!sec) { 65 sec = Date.now() / 1000 66 } 67 return moment.unix(sec).format('MM/DD/YYYY, h:mm:ss a') 68 } 69 70 module.exports = { 71 toInt, 72 toFloat, 73 stringifyValue, 74 floatifyValue, 75 formatTimestamp 76 }