跳至內容
Astera Technology

拆地址文字時保留中間空行

分行資料與原段文字一併保存。

下載完整個案資料及參考答案 ↓

來源格式與預期記錄

這是原創假設轉換例子。輸入限下列欄位的普通、無循環 JSON 形記錄,統一記錄格式及拒絕代碼由本例訂明。若換來源,先修改格式約定。

來源要有非空地址段及國家字樣。LF、CRLF 可分行,孤立 CR 拒絕。拆成 addressLines,不修剪或刪空行,並保存 sourceBlock。國家字樣只是來源文字,未表示通過地理核實。

可修改的假設轉換個案
個案輸入記錄(JSON)預期輸出(JSON)
拆分已提供地址{"block":"Demo Tower\nUnit 7","countryLabel":"Example"}{"ok":true,"value":{"addressLines":["Demo Tower","Unit 7"],"countryLabel":"Example","sourceBlock":"Demo Tower\nUnit 7"}}
拒絕沒有地址{"block":"","countryLabel":"Example"}{"ok":false,"error":"ADDRESS_EMPTY"}
保留中間空行{"block":"Demo Tower\n\nUnit 7","countryLabel":"Example"}{"ok":true,"value":{"addressLines":["Demo Tower","","Unit 7"],"countryLabel":"Example","sourceBlock":"Demo Tower\n\nUnit 7"}}
下載可編輯 CSV ↓

在本機執行轉換

把完整例子以 JavaScript 模組在 Node.js 執行,內含純轉換函數、三個輸入及寫明的預期輸出,對不上便由斷言停止。拒絕個案回傳 ok=false 及代碼,不回傳半份統一記錄。

完整函數及可執行個案
import assert from 'node:assert/strict';

function addressLines(i){
  const fail=error=>({ok:false,error});if(!i||typeof i.block!=='string'||!i.block||typeof i.countryLabel!=='string'||!i.countryLabel)return fail('ADDRESS_EMPTY');
  if(/\r(?!\n)/.test(i.block))return fail('ADDRESS_BREAK');
  return {ok:true,value:{addressLines:i.block.split(/\r?\n/),countryLabel:i.countryLabel,sourceBlock:i.block}};
}

// Original synthetic cases; expected outputs are literal records.
const cases = [
  {
    "label": "Split supplied address block",
    "input": {
      "block": "Demo Tower\nUnit 7",
      "countryLabel": "Example"
    },
    "expected": {
      "ok": true,
      "value": {
        "addressLines": [
          "Demo Tower",
          "Unit 7"
        ],
        "countryLabel": "Example",
        "sourceBlock": "Demo Tower\nUnit 7"
      }
    }
  },
  {
    "label": "Reject absent address",
    "input": {
      "block": "",
      "countryLabel": "Example"
    },
    "expected": {
      "ok": false,
      "error": "ADDRESS_EMPTY"
    }
  },
  {
    "label": "Preserve interior blank line",
    "input": {
      "block": "Demo Tower\n\nUnit 7",
      "countryLabel": "Example"
    },
    "expected": {
      "ok": true,
      "value": {
        "addressLines": [
          "Demo Tower",
          "",
          "Unit 7"
        ],
        "countryLabel": "Example",
        "sourceBlock": "Demo Tower\n\nUnit 7"
      }
    }
  }
];
for (const sample of cases) {
  const actual = addressLines(sample.input);
  assert.deepEqual(actual, sample.expected);
  console.log(sample.label, JSON.stringify(actual));
}
下載可執行例子 ↓

判清邊界個案

Demo Tower 與 Unit 7 之間空了一行,為何保留?

查看參考答案

來源本身有該行。輸出共三行,第二項為空字串;sourceBlock 保留原換行,方便還原。

相關資源