github.com/kosmosJS/engine-node@v0.0.0-20220426040216-d53e2a72192e/util/module.go (about)

     1  package util
     2  
     3  import (
     4  	"bytes"
     5  	"github.com/kosmosJS/engine"
     6  	"github.com/kosmosJS/engine-node/require"
     7  )
     8  
     9  type Util struct {
    10  	runtime *engine.Runtime
    11  }
    12  
    13  func (u *Util) format(f rune, val engine.Value, w *bytes.Buffer) bool {
    14  	switch f {
    15  	case 's':
    16  		w.WriteString(val.String())
    17  	case 'd':
    18  		w.WriteString(val.ToNumber().String())
    19  	case 'j':
    20  		if json, ok := u.runtime.Get("JSON").(*engine.Object); ok {
    21  			if stringify, ok := engine.AssertFunction(json.Get("stringify")); ok {
    22  				res, err := stringify(json, val)
    23  				if err != nil {
    24  					panic(err)
    25  				}
    26  				w.WriteString(res.String())
    27  			}
    28  		}
    29  	case '%':
    30  		w.WriteByte('%')
    31  		return false
    32  	default:
    33  		w.WriteByte('%')
    34  		w.WriteRune(f)
    35  		return false
    36  	}
    37  	return true
    38  }
    39  
    40  func (u *Util) Format(b *bytes.Buffer, f string, args ...engine.Value) {
    41  	pct := false
    42  	argNum := 0
    43  	for _, chr := range f {
    44  		if pct {
    45  			if argNum < len(args) {
    46  				if u.format(chr, args[argNum], b) {
    47  					argNum++
    48  				}
    49  			} else {
    50  				b.WriteByte('%')
    51  				b.WriteRune(chr)
    52  			}
    53  			pct = false
    54  		} else {
    55  			if chr == '%' {
    56  				pct = true
    57  			} else {
    58  				b.WriteRune(chr)
    59  			}
    60  		}
    61  	}
    62  
    63  	for _, arg := range args[argNum:] {
    64  		b.WriteByte(' ')
    65  		b.WriteString(arg.String())
    66  	}
    67  }
    68  
    69  func (u *Util) js_format(call engine.FunctionCall) engine.Value {
    70  	var b bytes.Buffer
    71  	var fmt string
    72  
    73  	if arg := call.Argument(0); !engine.IsUndefined(arg) {
    74  		fmt = arg.String()
    75  	}
    76  
    77  	var args []engine.Value
    78  	if len(call.Arguments) > 0 {
    79  		args = call.Arguments[1:]
    80  	}
    81  	u.Format(&b, fmt, args...)
    82  
    83  	return u.runtime.ToValue(b.String())
    84  }
    85  
    86  func Require(runtime *engine.Runtime, module *engine.Object) {
    87  	u := &Util{
    88  		runtime: runtime,
    89  	}
    90  	obj := module.Get("exports").(*engine.Object)
    91  	obj.Set("format", u.js_format)
    92  }
    93  
    94  func New(runtime *engine.Runtime) *Util {
    95  	return &Util{
    96  		runtime: runtime,
    97  	}
    98  }
    99  
   100  func init() {
   101  	require.RegisterNativeModule("util", Require)
   102  }