Skip to content

Instantly share code, notes, and snippets.

@gcoda
Last active December 18, 2018 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcoda/d5ad2cae104a644536cbd60dbe4af619 to your computer and use it in GitHub Desktop.
Save gcoda/d5ad2cae104a644536cbd60dbe4af619 to your computer and use it in GitHub Desktop.

Beware, It is really trivial and slow

JSON.parse(JSON.stringify()) is not really fast or efficient, but stringify has convenient replacer parameter

Useful for converting request query values to integers and booleans

Lets say you have lots of stuff in query

app.get('/query', (req, res) => res.send(req.query))
app.get('/infer', (req, res) => res.send(inferValues(req.query)))
GET /sign?url=https%3A%2F%2Fsource.unsplash.com%2Ffeatured%2F500x500&resize%5Bwidth%5D=200&resize%5Bheight%5D=150&resize%5BwithoutEnlargement%5D=true&output%5Bquality%5D=6&output%5Bformat%5D=jpeg

will output

{
  "url": "https://source.unsplash.com/featured/500x500",
  "resize": {
    "width": "200",
    "height": "150",
    "withoutEnlargement": "true"
  },
  "output": {
    "quality": "6",
    "format": "jpeg"
  }
}

GET /infer?...

{
  "url": "https://source.unsplash.com/featured/500x500",
  "resize": {
    "width": 200,
    "height": 150,
    "withoutEnlargement": true
  },
  "output": {
    "quality": 6,
    "format": "jpeg"
  }
}
const bool = { true: true, false: false, null: null }
const inferValue = (key, value) =>
bool.hasOwnProperty(value) //
? bool[value]
: parseFloat(value) || value
const inferValues = object => JSON.parse(JSON.stringify(object, inferValue))
module.exports = inferValues
{
"name": "infer-values",
"version": "1.0.2",
"repository": {
"type": "git",
"url": "git@gist.github.com:d5ad2cae104a644536cbd60dbe4af619.git"
},
"description": "Leveraging `replacer` parameter of `JSON.stringify`.",
"main": "index.js",
"scripts": {
"test": "node test.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
const assert = require('assert')
const inferValues = require('.')
assert.deepStrictEqual(
inferValues({
rotate: {
angle: 'null'
},
bool: 'false',
int: '555',
float: '56.33',
fancy: '4e3',
string: 'as is',
beware: '567e-2',
}),
{rotate: { angle: null },
bool: false,
int: 555,
float: 56.33,
fancy: 4000,
string: 'as is',
beware: 5.67,
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment