Skip to content

Instantly share code, notes, and snippets.

@zushenyan
Created May 30, 2018 16:13
Show Gist options
  • Save zushenyan/ed7d880197b31bcfb6e3c18f84d34283 to your computer and use it in GitHub Desktop.
Save zushenyan/ed7d880197b31bcfb6e3c18f84d34283 to your computer and use it in GitHub Desktop.
interface Field {
name: string;
path?: string;
}
interface Fields {
[name: string]: Section | Field;
}
interface Section extends Field {
fields: Fields;
}
interface Form {
id: string;
name: string;
containerPath: string | null;
fields: Section;
}
const log = (a: any) => console.log(JSON.stringify(a, undefined, 2));
const transPath = (p1: string, p2: string) => [p1, p2].filter(a => a).join('.');
const processPath = (node: Section | Field) : Section | Field => {
const { name, path, fields } = <Section>node;
node.path = path || name;
if (fields) {
const { path: parentPath = '' } = node;
Object.keys(fields).forEach((key) => {
const { name, path } = fields[key];
fields[key].path = path || transPath(parentPath, name);
return processPath(fields[key]);
});
}
return node;
};
const createField = (name: string = '', path?: string) : Field => {
return {
name,
path,
}
};
const createSection = ({ name = '', path = '', fields = {} }: Section) : Section => {
return {
name,
path,
fields
};
}
const createForm = (data: Form) : Form => {
const { fields } = data;
return {
...data,
fields: <Section>processPath(data.fields)
};
};
const signup = createForm({
id: 'signup',
name: 'signup',
containerPath: null,
// fields: createSection({
// name: '',
// fields: {},
// }),
fields: createSection({
name: 'aaa',
path: 'bbb',
fields: {
// email: createField('email'),
// password: createField('password'),
}
}),
});
log(signup)
const checkout = createForm({
id: 'college_location',
name: 'college_location',
containerPath: null,
fields: createSection({
name: 'checkout',
path: 'education.list[0].checkout',
fields: {
cardInfo: createSection({
name: 'cardInfo',
fields: {
cardNumber: createField('cardNumber'),
}
}),
billingInfo: createSection({
name: 'billingInfo',
path: 'override!!!!',
fields: {
firstName: createField('firstName', 'hahahah'),
}
}),
test: createField('test'),
}
})
});
log(checkout);
// const sectionName = checkout.fields.path;
// const cardInfoSectionName = checkout.fields.fields.cardInfo.name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment