(data: DataMap, path: string)
| 369 | * @returns 是否删除成功 |
| 370 | */ |
| 371 | export function deleteData(data: DataMap, path: string): boolean { |
| 372 | if (!isValidJsonPointer(path) || path === '') { |
| 373 | return false; |
| 374 | } |
| 375 | |
| 376 | const tokens = parseJsonPointer(path); |
| 377 | if (tokens.length === 0) { |
| 378 | return false; |
| 379 | } |
| 380 | |
| 381 | // 遍历到父节点 |
| 382 | let current: DataValue | undefined = data; |
| 383 | const parentTokens = tokens.slice(0, -1); |
| 384 | const lastToken = tokens[tokens.length - 1]!; |
| 385 | |
| 386 | for (const token of parentTokens) { |
| 387 | if (current === null || current === undefined) { |
| 388 | return false; |
| 389 | } |
| 390 | |
| 391 | if (Array.isArray(current)) { |
| 392 | const index = parseInt(token, 10); |
| 393 | if (isNaN(index) || index < 0 || index >= current.length) { |
| 394 | return false; |
| 395 | } |
| 396 | current = current[index] as DataValue | undefined; |
| 397 | } |
| 398 | else if (typeof current === 'object') { |
| 399 | const obj = current as DataMap; |
| 400 | if (!(token in obj)) { |
| 401 | return false; |
| 402 | } |
| 403 | current = obj[token]; |
| 404 | } |
| 405 | else { |
| 406 | return false; |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | // 删除值 |
| 411 | if (current === null || current === undefined) { |
| 412 | return false; |
| 413 | } |
| 414 | |
| 415 | if (Array.isArray(current)) { |
| 416 | const index = parseInt(lastToken, 10); |
| 417 | if (isNaN(index) || index < 0 || index >= current.length) { |
| 418 | return false; |
| 419 | } |
| 420 | current.splice(index, 1); |
| 421 | return true; |
| 422 | } |
| 423 | |
| 424 | if (typeof current === 'object') { |
| 425 | const obj = current as DataMap; |
| 426 | if (!(lastToken in obj)) { |
| 427 | return false; |
| 428 | } |
no test coverage detected