项目作者: thanhpk

项目描述 :
Dead simple cross-language string formatter
高级语言: Go
项目地址: git://github.com/thanhpk/stringf.git
创建时间: 2017-06-06T04:17:56Z
项目社区:https://github.com/thanhpk/stringf

开源协议:Apache License 2.0

下载


Sringf License npm version

Dead simple cross-language string formatter

No dependencies, O(N*m)

Note: Key must only contains alphabet and _. Invalid keys will be ignore

Usage

go

  1. import (
  2. "fmt"
  3. "github.com/thanhpk/stringf"
  4. )
  5. func main() {
  6. str := stringf.Format("hi {name}, here is your number {{2108 and {name2}.", map[string]string{
  7. "name": "Kieu Thanh", // key should not contains spaces
  8. })
  9. fmt.Println(str)
  10. }
  11. // hi Kieu Thanh, here is your number {2108 and {name2}.

js

  1. var stringf = require("stringf")
  2. var str = stringf.Format("hi {name}, here is your number {{2108 and {name2}.", {
  3. name: "Thanh",
  4. })
  5. console.log(str)
  6. // hi Thanh, here is your number {2108 and {name2}.

Test

Go

  1. go test

Js

  1. npm test

Testcase

String Parameter map Output
hi {name} name: Thanh hi Thanh
hi {num} num: 2108 hi 2108
{{abc} abc: bcd {abc

Pseudocode to implement in your own language

input:

  1. a string, s
  2. a map string to string, paramMap

output:

a string with param replaced

  1. let ESCCHAR '{', ESCCHAREND '}', i 0, output ""
  2. while i < length(s) do
  3. if s[i] = ESCCHAR then
  4. let j i + 1
  5. while j <= length(s) and s[j] = ESCCHAR do
  6. j j + 1
  7. if (j - i) mod 2 = 0 then
  8. output output + ESCCHAR
  9. if (j - i) mod 2 0 then
  10. let param "" (parse parameter key)
  11. while j < length(s) and s[j] ESCCHAREND do
  12. param param + s[j]
  13. j j + 1
  14. if length(param) > 0 then
  15. output output + paramMap[param]
  16. if j = length(s) then
  17. return output
  18. else if s[j = ESCCHAREND then
  19. j j + 1
  20. i j
  21. output output + s[i]
  22. i i + 1
  23. return output