W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
你有一組數(shù)據(jù),需要在多個過程、可能變換的方式下處理。
使用修飾模式來構(gòu)造如何更改應用。
miniMarkdown = (line) ->
if match = line.match /^(#+)\s*(.*)$/
headerLevel = match[1].length
headerText = match[2]
"<h#{headerLevel}>#{headerText}</h#{headerLevel}>"
else
if line.length > 0
"<p>#{line}</p>"
else
''
stripComments = (line) ->
line.replace /\s*\/\/.*$/, '' # Removes one-line, double-slash C-style comments
class TextProcessor
constructor: (@processors) ->
reducer: (existing, processor) ->
if processor
processor(existing or '')
else
existing
processLine: (text) ->
@processors.reduce @reducer, text
processString: (text) ->
(@processLine(line) for line in text.split("\n")).join("\n")
exampleText = '''
# A level 1 header
A regular line
// a comment
## A level 2 header
A line // with a comment
'''
processor = new TextProcessor [stripComments, miniMarkdown]
processor.processString exampleText
# => "<h1>A level 1 header</h1>\n<p>A regular line</p>\n\n<h2>A level 2 header</h2>\n<p>A line</p>"
<h1>A level 1 header</h1>
<p>A regular line</p>
<h2>A level 1 header</h2>
<p>A line</p>
TextProcessor服務有修飾的作用,可將個人、專業(yè)文本處理器綁定在一起。這使miniMarkdown和stripComments組件只專注于處理一行文本。未來的開發(fā)人員只需要編寫函數(shù)返回一個字符串,并將它添加到陣列的處理器即可。
我們甚至可以修改現(xiàn)有的修飾對象動態(tài):
smilies =
':)' : "smile"
':D' : "huge_grin"
':(' : "frown"
';)' : "wink"
smilieExpander = (line) ->
if line
(line = line.replace symbol, "<img src='#{text}.png' alt='#{text}' />") for symbol, text of smilies
line
processor.processors.unshift smilieExpander
processor.processString "# A header that makes you :) // you may even laugh"
# => "<h1>A header that makes you <img src='smile.png' alt='smile' /></h1>"
processor.processors.shift()
# => "<h1>A header that makes you :)</h1>"
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: