Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/python-wasm
Path: blob/main/python/pylang/src/utils.py
1396 views
1
# mypy
2
from __python__ import hash_literals, Object # type: ignore
3
4
from typing import Any, Callable, Literal, Optional, Union
5
6
7
def array_to_hash(a: list[str]) -> dict[str, bool]:
8
ret = {}
9
for i in range(len(a)):
10
ret[a[i]] = True
11
return ret
12
13
14
def characters(str_: str) -> list[str]:
15
return str_.split("")
16
17
18
def repeat_string(str_: str, i: int) -> str:
19
if i <= 0:
20
return ""
21
if i is 1:
22
return str_
23
d = repeat_string(str_, i >> 1)
24
d += d
25
if i & 1:
26
d += str_
27
return d
28
29
30
class DefaultsError(ValueError):
31
def __init__(self, name: str, defs: dict):
32
ValueError.__init__(
33
self,
34
name + ' is not a supported option. Supported options are: ' +
35
str(Object.keys(defs)))
36
37
38
has_prop = Object.prototype.hasOwnProperty.call.bind(
39
Object.prototype.hasOwnProperty)
40
41
42
def defaults(args: Union[Literal[True], dict], defs: dict, croak: Callable):
43
if args is True:
44
args = {}
45
ret = args or {}
46
if croak:
47
for i in ret:
48
if not has_prop(defs, i):
49
raise DefaultsError(i, defs)
50
51
for i in defs:
52
ret[i] = args[i] if args and has_prop(args, i) else defs[i]
53
return ret
54
55
56
def merge(obj: dict, ext: dict) -> dict:
57
for i in ext:
58
obj[i] = ext[i]
59
return obj
60
61
62
def noop() -> None:
63
pass
64
65
66
def push_uniq(array, el) -> None:
67
if not array.includes(el):
68
array.push(el)
69
70
71
def string_template(text: str, props: dict) -> str:
72
def f(str_, p):
73
return props[p]
74
75
# js replace takes function
76
return text.replace(r"%js /\{(.+?)\}/g", f) # type: ignore
77
78
79
def make_predicate(words: Union[str, list[str]]) -> dict[str, Literal[True]]:
80
if isinstance(words, str):
81
words = words.split(" ")
82
a = Object.create(None)
83
for k in words:
84
a[k] = True
85
return a
86
87
88
def cache_file_name(src: str, cache_dir: str) -> Union[None, str]:
89
if cache_dir:
90
src = str.replace(src, '\\', '/')
91
return cache_dir + '/' + str.lstrip(
92
str.replace(src, '/', '-') + '.json', '-')
93
return None
94
95
96
# This charAt is defined in Javascript and is definitely not s[n],
97
# so here's a version that will work in pure Python *and* pylang.
98
def charAt(s: str, n: int) -> str:
99
try:
100
return s.charAt(n) # type: ignore
101
except:
102
if n < 0 or n >= len(s): return ''
103
return s[n]
104
105
106
# Version of indexOf that works in pure python and pylang
107
def indexOf(s: str, t: str) -> int:
108
try:
109
return s.indexOf(t) # type: ignore
110
except:
111
# pure python
112
try:
113
return s.index(t)
114
except:
115
return -1
116
117
118
def startswith(s: str, t: str) -> bool:
119
try:
120
# pylang
121
return s.startsWith(t) # type: ignore
122
except:
123
# pure python
124
return s.startswith(t)
125
126