Skip to content

Instantly share code, notes, and snippets.

@pagewang0 pagewang0/groupby.js
Created Dec 13, 2018

Embed
What would you like to do?
// 成绩等级分为A、B和C三级
function getGrade(score) {
return score < 60 ? 'C' :
score < 80 ? 'B' : 'A';
};
// 学生及其成绩
let students = [
{ name: '张三', score: 84 },
{ name: '李四', score: 58 },
{ name: '王五', score: 99 },
{ name: '赵六', score: 69 }
];
function groupBy(students) {
return [{}].concat(students).reduce((s, c) => {
const grade = getGrade(c.score);
!s[grade] && (s[grade] = []);
s[grade].push(c);
return s;
})
}
// console.log(groupBy(students));
function parse(input) {
if (/^Array/.test(input)) {
const type = /Array<(.+)>/.exec(input)[1];
return {
type: 'Array',
typeArgs: parse(type)
};
}
return { type: input };
}
const input = ["int", "string", "bool", "Array<int>", "Array<Array<int>>", "Array<Array<Array<int>>>"];
input.forEach(d => {
console.log('----------------------');
console.log(JSON.stringify(parse(d), null, '\t'));
});
const assert = require('assert');
let tree = {
id: '1',
label: 'first',
children: [
{
id: '2',
label: 'second'
},
{
id: '3',
label: 'third',
children: [
{
id: '4',
label: 'fourth'
},
{
id: '5',
label: 'fifth'
}
]
}
]
};
function findNodeById(root = {}, id) {
const p = root;
if (!root.id) {
return;
}
if (root.id === id) {
return p;
}
if (!root.children) {
return;
}
for (let i = 0; i < root.children.length; i++) {
const ret = findNodeById(root.children[i], id);
if (ret) {
return ret
}
}
}
assert.equal(findNodeById(tree, '1').label, 'first');
assert.equal(findNodeById(tree, '2').label, 'second');
assert.equal(findNodeById(tree, '3').label, 'third');
assert.equal(findNodeById(tree, '4').label, 'fourth');
assert.equal(findNodeById(tree, '5').label, 'fifth');
@dannnney

This comment has been minimized.

Copy link

commented Dec 14, 2018

cool ,尝试 parse 一下这个 case :
Map<string, Array<Map<int, string>>>
Map<Array<Map<int, string>>, string>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.