set-value.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. function valueType (value) {
  2. if (value === undefined) return 'undefined'
  3. if (Array.isArray(value)) return 'array'
  4. if (typeof value === 'object') return 'object'
  5. return 'scalar'
  6. }
  7. function setLastValue (context, step, currentValue, entryValue) {
  8. switch (valueType(currentValue)) {
  9. case 'undefined':
  10. if (step.append) {
  11. context[step.key] = [entryValue]
  12. } else {
  13. context[step.key] = entryValue
  14. }
  15. break
  16. case 'array':
  17. context[step.key].push(entryValue)
  18. break
  19. case 'object':
  20. return setLastValue(currentValue, { type: 'object', key: '', last: true }, currentValue[''], entryValue)
  21. case 'scalar':
  22. context[step.key] = [context[step.key], entryValue]
  23. break
  24. }
  25. return context
  26. }
  27. function setValue (context, step, currentValue, entryValue) {
  28. if (step.last) return setLastValue(context, step, currentValue, entryValue)
  29. var obj
  30. switch (valueType(currentValue)) {
  31. case 'undefined':
  32. if (step.nextType === 'array') {
  33. context[step.key] = []
  34. } else {
  35. context[step.key] = Object.create(null)
  36. }
  37. return context[step.key]
  38. case 'object':
  39. return context[step.key]
  40. case 'array':
  41. if (step.nextType === 'array') {
  42. return currentValue
  43. }
  44. obj = Object.create(null)
  45. context[step.key] = obj
  46. currentValue.forEach(function (item, i) {
  47. if (item !== undefined) obj['' + i] = item
  48. })
  49. return obj
  50. case 'scalar':
  51. obj = Object.create(null)
  52. obj[''] = currentValue
  53. context[step.key] = obj
  54. return obj
  55. }
  56. }
  57. module.exports = setValue