Last active
October 12, 2016 22:19
-
-
Save SuperPaintman/d9b06d8251f100475e80e27a09169f95 to your computer and use it in GitHub Desktop.
Sweet.js - set default
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
syntax setd = (ctx) => { | |
const dummy = #`dummy`.get(0); | |
let result = #``; | |
ctx.expand('expr'); | |
ctx.reset(); | |
const selectors = []; | |
let next = ctx.next().value; | |
while (!next.isPunctuator('=')) { | |
selectors.push(next); | |
next = ctx.next().value; | |
} | |
const operator = next; | |
if (!operator.isPunctuator('=')) { | |
throw new Error(`unknown syntax: "${operator}". Must be "="`); | |
} | |
selectors.forEach((selector) => { | |
if (!(selector.isPunctuator('.') | |
|| selector.isBrackets() | |
|| selector.isIdentifier() | |
)) { | |
throw new Error(`unknown syntax: "${selector}"`); | |
} | |
}); | |
const exprValue = ctx.next().value; | |
if (selectors.length > 1) { | |
const len = selectors.length; | |
for (let i = 0; i < len - 2; i++) { | |
const otherSlectors = selectors | |
.slice(0, i + 1); | |
const nextSelector = selectors[i + 1]; | |
if (nextSelector.isPunctuator('.')) { | |
result = result.concat(#` | |
if (${otherSlectors} == null) { | |
${otherSlectors} = {}; | |
} | |
`); | |
} else if (nextSelector.isBrackets()) { | |
result = result.concat(#` | |
if (${otherSlectors} == null) { | |
${otherSlectors} = []; | |
} | |
`); | |
} | |
} | |
} | |
return result.concat(#` | |
if (${selectors} == null) { | |
${selectors} = ${exprValue} | |
} | |
`); | |
} | |
function test(options) { | |
setd options.deep.deep.deep.c = { text: 'hello there C' }; | |
return JSON.stringify(options, true, 2); | |
} | |
console.log(test({ | |
deep: { | |
a: 1 | |
} | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment