- 實現一個檢驗對象是否循環指向的方法
function isCyclic (obj) {
const arr = [];
function check(childObj) {
let res = false
for(let i in childObj) {
if (typeof childObj[i] === 'object' && childObj[i]!==null){
if(!arr.includes(childObj[i])) {
arr.push(childObj[i])
res = check(childObj[i])
} else {
return true
}
}
}
return res
}
return check(obj)
}
console.log(isCyclic(window));
console.log(isCyclic({}));
var o = {}; o.o = o;
console.log(isCyclic(o));
var obj = { foo: { bar: { baz: { qux:{} } } } };
obj.foo.bar.baz.qux = obj.foo;
console.log(isCyclic(obj));
- 實現一個評星方法
function getRate (score, total) {
let err = 'error'
if (typeof score !== 'number') {
return err;
}
if (total !== undefined && (typeof total) !== 'number') {
return err;
}
total = total === undefined ? 5 : total;
score = Math.round(score)
if (score < 0 || score > total) {
return err;
}
if (total <= 0 || total.toString().includes('.')) {
return err;
}
let res = Array(total).fill('★',0, score).fill('☆', score);
return res.join('');
}
console.log(getRate(4));
console.log(getRate(4, 8));
console.log(getRate(3.4));
console.log(getRate(5, 2));
console.log(getRate(-2));
console.log(getRate(3, 5.5));
- 判斷括號匹配
function isValid (str) {
let endChar = [];
for(let i = 0; i < str.length; i++) {
switch (str[i]) {
case '(':
endChar.push(')')
break;
case '[':
endChar.push(']')
break;
case '{':
endChar.push('}')
break;
default:
if (endChar.pop() !== str[i]) {
return false
}
break;
}
}
return endChar.length === 0
}
console.log(isValid('('));
console.log(isValid('()'));
console.log(isValid('()[]{}'));
console.log(isValid('{()[]}'));
console.log(isValid('(]'));
console.log(isValid('([)]'));
console.log(isValid('({}[]([]))'));
- 給定一個編碼字符,按編碼規則進行編碼,輸出字符串
function decodeString (str) {
let letterReg = /(?<count>\d+)\[(?<letter>[a-zA-Z]*)\]/
function replaceStr (count, letter) {
return Array(count).fill(letter).join('')
}
while(letterReg.test(str)) {
const {count, letter} = str.match(letterReg).groups
str = str.replace(letterReg, replaceStr(Number(count), letter))
}
return str;
}
const s = '3[a]2[bc]';
console.log(decodeString(s));
const s2 = '3[a2[c]]';
console.log(decodeString(s2));
const s3 = '2[abc]3[cd]ef';
console.log(decodeString(s3));
- 平鋪節點數組轉嵌套樹
function arrayToTree(arr) {
const ans = [];
let pos = []
for (let obj of arr) {
setPos(obj.depth)
arrayToTreeHelper(pos, obj.depth);
}
return ans;
function setPos(depth) {
if (depth <= pos.length) {
pos = pos.slice(0,depth)
}
pos[depth-1] = (pos[depth-1] || 0) + 1
}
function arrayToTreeHelper(pos, depth) {
if (depth === 1) {
ans.push({
depth: depth
})
return;
}
pos.reduce((end,curt,index) => {
if (index === 0) {
return end[curt-1]
}
end.children = end.children || []
if(end.children[curt-1] === null || end.children[curt-1] === undefined) {
end.children[curt-1] = {
depth: depth
}
}
return end.children[curt-1]
}, ans)
}
}
const arr = [
{ depth: 1 },
{ depth: 2 },
{ depth: 3 },
{ depth: 3 },
{ depth: 2 },
{ depth: 1 },
{ depth: 2 },
]
console.log(JSON.stringify(arrayToTree(arr)))