I have to convert some JS functions to snowflake udfs. It works successfully with hardcoded sample data but I can’t make it accept user input as arguments. I know the UDF’s create statement is supposed to take the input but I cannot make it work.
JavaScript
x
11
11
1
CREATE OR REPLACE FUNCTION findAndReplace()
2
RETURNS variant
3
LANGUAGE JAVASCRIPT
4
AS
5
$$
6
return execute(map,value);
7
$$
8
;
9
10
select findAndReplace();
11
Thanks for the help.
Advertisement
Answer
Assuming that arguments to provide are inside map.set("SKU","Common Measurement (L x W)^Manufacturer Color/Finish");
the function signature has to be changed to findAndReplace(ARG1 TEXT, ARG2 TEXT)
:
JavaScript
1
30
30
1
CREATE OR REPLACE FUNCTION findAndReplace(ARG1 TEXT, ARG2 TEXT)
2
RETURNS variant
3
LANGUAGE JAVASCRIPT
4
AS
5
$$
6
const execute = (productMap, values) => {
7
const split = values.split(",");
8
const value = productMap.get(split[0]);
9
try {
10
if (split.length > 2) {
11
if (value != null) {
12
const from = split[1].replaceAll("'", "");
13
const to = split[2].replaceAll("'", "");
14
return value.replaceAll(from,to);
15
}
16
}
17
}catch{
18
console.log("Error in executing FindAndReplace Rule ");
19
}
20
return "n/a";
21
}
22
23
//Example
24
var map = new Map()
25
map.set(ARG1, ARG2); // <-- HERE
26
const value = "SKU,'Color/','#'";
27
return execute(map,value);
28
$$
29
;
30
Function all:
JavaScript
1
2
1
select findAndReplace('SKU', 'Common Measurement (L x W)^Manufacturer Color/Finish');
2