Skip to content

Commit

Permalink
fix: handle explicit undefined values
Browse files Browse the repository at this point in the history
  • Loading branch information
Dean James committed Dec 23, 2022
1 parent 1d3a650 commit 4d9a2d8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
10 changes: 5 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { isNull, isBoolean, isNumber, isString, isArray, isObject, isEmpty, fromPairs, keys, map, repeat } = require('lodash')
const { isNull, isBoolean, isNumber, isString, isArray, isObject, isUndefined, isEmpty, fromPairs, keys, map, repeat } = require('lodash')
const { parse: parseLua } = require('luaparse')

const formatLuaString = (string, singleQuote) => (singleQuote ? `'${string.replace(/'/g, "\\'")}'` : `"${string.replace(/"/g, '\\"')}"`)
Expand Down Expand Up @@ -43,12 +43,12 @@ const format = (value, options = { eol: '\n', singleQuote: true, spaces: 2 }) =>
const spaces = isNumber(options.spaces) ? repeat(' ', options.spaces * (i + 1)) : repeat(options.spaces, i + 1)
const spacesEnd = isNumber(options.spaces) ? repeat(' ', options.spaces * i) : repeat(options.spaces, i)
return `{${eol}${keys(value)
.map(key => `${spaces}${formatLuaKey(key, options.singleQuote)} = ${rec(value[key], i + 1)},`)
.join(eol)}${eol}${spacesEnd}}`
.map(key => (isUndefined(value[key]) ? undefined : `${spaces}${formatLuaKey(key, options.singleQuote)} = ${rec(value[key], i + 1)},`))
.join(eol)}${eol}${spacesEnd}}`.replace('\n\n', '\n')
}
return `{${keys(value)
.map(key => `${formatLuaKey(key, options.singleQuote)}=${rec(value[key], i + 1)},`)
.join('')}}`
.map(key => (isUndefined(value[key]) ? undefined : `${formatLuaKey(key, options.singleQuote)}=${rec(value[key], i + 1)},`))
.join('')}}`.replace('\n\n', '\n')
}
throw new Error(`can't format ${typeof value}`)
}
Expand Down
9 changes: 9 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,12 @@ jsonDoubleQuote._object2 = mapKeys(jsonDoubleQuote._object2, (_, key) => key.rep
const luaDoubleQuote = lua.replace(/'/g, '"')
equal(format(jsonDoubleQuote, { singleQuote: false }), luaDoubleQuote)
deepEqual(parse(luaDoubleQuote), jsonDoubleQuote)

const jsonUndefinedValue = {
_undefined: undefined,
_string: 'string',
}
const luaUndefinedValue = `return {
_string = 'string',
}`
equal(format(jsonUndefinedValue), luaUndefinedValue)

0 comments on commit 4d9a2d8

Please sign in to comment.