Skip to content

Instantly share code, notes, and snippets.

@SuperPaintman
Last active October 12, 2016 22:19
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 SuperPaintman/d9b06d8251f100475e80e27a09169f95 to your computer and use it in GitHub Desktop.
Save SuperPaintman/d9b06d8251f100475e80e27a09169f95 to your computer and use it in GitHub Desktop.
Sweet.js - set default
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