Explicitly Import only one function from exported constant which stores multiple functions - ecmascript-6

I've a Constant like below stored in a file helper.js
export const Helper = {
a() {
return "This is just a string"
},
convertToSlug(str) {
return str
.toLowerCase()
.replace(/[^\w ]+/g, "")
.replace(/ +/g, "-")
}
}
From this i want to import only convertToSlug function in another file like below
import { convertToSlug } from "helper.js"
How to do that? I tried the same but getting error
"export 'convertToSlug' was not found in '#/utils/helper'

If you want import { convertToSlug } from "helper.js" to work then you need to have an export named convertToSlug. Right now you've grouped everything inside Helper but there doesn't seem to be any reason for that. It looks like most likely you'd want
export function a() {
return "This is just a string"
}
export function convertToSlug(str) {
return str
.toLowerCase()
.replace(/[^\w ]+/g, "")
.replace(/ +/g, "-")
}

Related

How to add spacing between key value pairs when writing JSON to file

I have a json file that displays values in one very long line.
I would like to show it in more clean and easy to read manner with spacing and multiple lines.
Below is the code for writing json object to file.
var jsonEncoded = jsonEncode(_json);
configFile.writeAsString(jsonEncoded);
Any advice? Thank you.
Here is how you can format your JSON.
import 'dart:convert';
void main() {
print(prettyJson({"glossary":{"title":"example glossary"}}));
}
String prettyJson(dynamic json) {
var spaces = ' ' * 4;
var encoder = JsonEncoder.withIndent(spaces);
return encoder.convert(json);
}
Output:
{
"glossary": {
"title": "example glossary"
}
}
Try out to put your JSON into that function and get the output.

How to interact with multiple webelments in testcafe using json file

I want to interact with multiple elements like multiple checkboxes radio buttons, buttons etc. I want to store the label/name of the elements into the json file. How can I interact with multiple elements using the name from Json file in testcafe
Take a look at the data-driven test example. It shows how to load data from a JSON file. You can use the loaded data in Selector expressions like Selector('button').withText(data.buttons[0]) to reference elements.
I don't know your particular use case, but speaking purely technically, you can easily do what you're asking:
Resources/names.json:
{
"buttons": [
"First Click",
"Second Click"
],
"checkboxes": [
"Choice1",
"Choice2"
]
}
then I can lod the file in a test file and work with the values:
import { getBaseUrl } from '../Helpers/baseUrl';
import { getEnv } from '../Helpers/env';
import Webelements from '../Objects/webelements'
const baseUrl = getBaseUrl();
const env = getEnv();
const webelements = require('../Resources/names.json');
fixture `Webelements`
.page(baseUrl);
test
('Access Webelements From Json', async t => {
webelements.buttons.forEach((button) => {
console.log(button);
});
webelements.checkboxes.forEach((checkbox) => {
console.log(checkbox)
});
});
this will print the following into the console:
First Click
Second Click
Choice1
Choice2
Another solution could be using classes:
Objects/webelements.js:
class Checkboxes {
constructor () {
this.choices = {
1: "Choice1",
2: "Choice2"
}
}
}
class Buttons {
constructor () {
this.names = ["First Click", "Second Click"]
}
}
class Webelements {
constructor () {
this.checkboxes = new Checkboxes();
this.buttons = new Buttons();
}
}
export default new Webelements();
and use it like this:
test
('Access Webelements From Classes', async t => {
Object.entries(Webelements.checkboxes.choices).forEach(([key, val]) => {
console.log(key + " - " + val);
})
Webelements.buttons.names.forEach((name) => {
console.log(name)
});
});
this will output:
1 - Choice1
2 - Choice2
First Click
Second Click
So, there're options, but the point is that some solutions are better for some situations. I have very little idea about your situation, so you have to make this decision for yourself.

Why does the example from official docs of skrape{it} not compile

There is example piece of code from official website of skrape{it}. It is about extracting data from website. I'm using library version 1.0.0-alpha6
import it.skrape.core.htmlDocument
import it.skrape.selects.and
import it.skrape.selects.eachImage
import it.skrape.selects.eachText
import it.skrape.selects.html5.a
import it.skrape.selects.html5.div
import it.skrape.selects.html5.p
import it.skrape.selects.html5.span
import org.junit.jupiter.api.Test
// just some object where we will store our scraped data
data class MyExtractedData(
var httpMessage: String = "",
var userName: String = "",
var repositoryNames: List<String> = emptyList(),
var theThirdRepositoriesName: String = "",
var firstThreeHrefs: List<String> = emptyList(),
var overviewLink: String = "",
var firstThreeImageSources: List<String> = emptyList(),
var title: String = "",
var starsCount: String = ""
)
fun main() {
val extracted = skrape { // 1️⃣
url = "https://github.com/skrapeit"
extractIt<MyExtractedData> { it ->
it.httpMessage = status { message } // 2️⃣
htmlDocument { // 3️⃣
relaxed = true // 4️⃣
it.userName = ".h-card .p-nickname" { findFirst { text } } // 5️⃣
val repositories = span(".repo") { findAll { this }} // 6️⃣
println("hello world") // 7️⃣
it.repositoryNames = repositories.filter { it.text.contains("skrape") }.eachText // 8️⃣
it.theThirdRepositoriesName = span(".repo") {
2 { text } // 9️⃣
}
it.firstThreeImageSources = findAll { eachImage.map { image -> image.value } }.take(3) // 1️⃣0️⃣
it.firstThreeHrefs = findAll { eachHref }.take(3) // 1️⃣1️⃣
it.overviewLink = findAll { eachLink["Overview"] ?: "not found" } // 1️⃣2️⃣
it.title = titleText // 1️⃣3️⃣
// *️⃣
it.starsCount = div { // 1️⃣5️⃣
withClass = "pinned-item-list-item"
findFirst {
p { // 1️⃣6️⃣
findSecond {
a {
// 1️⃣7️⃣
withClass = "pinned-item-meta" and "muted-link" // 1️⃣8️⃣
withAttribute = "href" to "/skrapeit/skrape.it/stargazers" // 1️⃣9️⃣
findFirst {
ownText
}
}
}
}
}
}
}
}
}
println(extracted)
}
This piece of code simply does not compile. All possible imports had been done.
Errors:
Unresolved reference: status
Unresolved reference: message
Unresolved reference: relaxed
Function invocation 'eachText()' expected (line with 8️⃣ comment)
Expression '2' of type 'Int' cannot be invoked as a function. The function 'invoke()' is not found (line with 9️⃣ comment)
Type mismatch. Required: List. Found: List (line with 1️⃣0️⃣ comment)
And that's not all. There are lots of errors almost in every line. Where is the mistake?
Thank you!
I know I has been a while, but I was looking at the scrape{it} yesterday for the first time and face the same issue as you did.
The guys have an error on the official docs (probably it is just a way it used to work before).
To make it work, you need to change the top of the function slightly:
val extracted = skrape(HttpFetcher) { // 1️⃣
request {
url = "https://github.com/skrapeit"
}
It did a trick for me, hope will help someone as well.

Typescript infer return type from passed functions return type

I might be trying to achieve the impossible but here goes.
I want to define a function ( function A ) which will return the same type as a new function passed into the parameter of function A.
e.g.
export function test<T> ( arg:Function ):T {
return arg;
}
function a():string {
return 'a';
}
function b():number {
return 0;
}
let aVal:string = test(a);
let bVal:number = test(b);
Obviously this will allow me to strongly type my responses for some compile time errors.
Does anyone have any ideas or know if I'm just dreaming.
** Note: Code slapped together for demo **
Cheers
How about this?
function test<T>(arg: () => T): T {
return arg();
}
function a(): string {
return 'a';
}
function b(): number {
return 0;
}
let aVal: string = test(a);
let bVal: number = test(b);
Instead of using the Function interface we defined arg as a function that takes no arguments and returns something of type T. The actual type T then can be defined by the function that's passed in.

How to hide library source code in Google way?

For instance, I have a library and I would like to protect the source code to being viewed. The first method that comes to mind is to create public wrappers for private functions like the following
function executeMyCoolFunction(param1, param2, param3) {
return executeMyCoolFunction_(param1, param2, param3);
}
Only public part of the code will be visible in this way. It is fine, but all Google Service functions look like function abs() {/* */}. I am curious, is there an approach to hide library source code like Google does?
Edit 00: Do not "hide" a library code by using another library, i.e. the LibA with known project key uses the LibB with unknown project key. The public functions code of LibB is possible to get and even execute them. The code is
function exploreLib_(lib, libName) {
if (libName == null) {
for (var name in this) {
if (this[name] == lib) {
libName = name;
}
}
}
var res = [];
for (var entity in lib) {
var obj = lib[entity];
var code;
if (obj["toSource"] != null) {
code = obj.toSource();
}
else if (obj["toString"] != null) {
code = obj.toString();
}
else {
var nextLibCode = exploreLib_(obj, libName + "." + entity);
res = res.concat(nextLibCode);
}
if (code != null) {
res.push({ libraryName: libName, functionCode: code });
}
}
return res;
}
function explorerLibPublicFunctionsCode() {
var lstPublicFunctions = exploreLib_(LibA);
var password = LibA.LibB.getPassword();
}
I don't know what google does, but you could do something like this (not tested! just an idea):
function declarations:
var myApp = {
foo: function { /**/ },
bar: function { /**/ }
};
and then, in another place, an anonymous function writes foo() and bar():
(function(a) {
a['\u0066\u006F\u006F'] = function(){
// here code for foo
};
a['\u0062\u0061\u0072'] = function(){
// here code for bar
};
})(myApp);
You can pack or minify to obfuscate even more.
Edit: changed my answer to reflect the fact that an exception's stacktrace will contain the library project key.
In this example, MyLibraryB is a library included by MyLibraryA. Both are shared publicly to view (access controls) but only MyLibraryA's project key is made known. It appears it would be very difficult for an attacker to see the code in MyLibraryB:
//this function is in your MyLibraryA, and you share its project key
function executeMyCoolFunction(param1, param2, param3) {
for (var i = 0; i < 1000000; i++) {
debugger; //forces a breakpoint that the IDE cannot? step over
}
//... your code goes here
//don't share MyLibraryB project key
MyLibraryB.doSomething(args...);
}
but as per the #megabyte1024's comments, if you were to cause an exception in MyLibraryB.doSomething(), the stacktrace would contain the project key to MyLibraryB.