Add and subtract from input field onkeyup vue3

I have a fixed number 100. When a user enters in numbers, I’d like these figures to be subtracted from the total of 100 but if deleted, the difference added back to the 100 total. This is what I have tried but it keeps subtracting without adding the difference back when I delete figures:

html:

                <input
                  type="number"
                  placeholder="Ex: 40"
                  v-model="e"
                  @keyup="validate()"
                  @blur="validate()"
                  required
                />

js:

const total = ref(100);
const e = ref("");

    const validate = (e) => {
            if(e.value){
        totalPercentages.value = total.value - e.value
      }
    };

how to push object into an array [duplicate]

hello I am trying to push objects into an array, I do it in two different scenarios where one works but other does not?
optIn.push({ cardId, cardName})
The above one works
optInUsers = optInUsers.push({ userEmail : session.user.email, userName : session.user.name})
this one does not work though? both optIn and optInUsers are arrays.
Are session.user.email not strings which can be used in objects? as soon as i do the push the optInUsers gets converted to Int32 type?

Render specific child nodes of specific parent nodes using Angular Material Tree

Consider the below Array Data:

const Tree_Data = [
  {
    id: 'A',
    friendlyName: 'Account',
    columns: [
      {
        id: 'a1',
        friendlyName: 'Account Code',
      },
      {
        id: 'a2',
        friendlyName: 'Account Value',
      }
    ]
  },
  {
    id: 'C',
    friendlyName: 'Customer',
    columns: [
      {
        id: 'c1',
        friendlyName: 'Customer Code',
      },
      {
        id: 'c2',
        friendlyName: 'Customer Value',
      }
    ]
  }
]

HTML file below:

<input [(ngModel)]="searchString" />
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <mat-tree-node
    *matTreeNodeDef="let node"
    [style.display]="
      filterLeafNode(node) ? 'none' : 'block'
    "
    matTreeNodeToggle
    matTreeNodePadding
    matTreeNodePaddingIndent="20"
  >
    <button class="button__arrow" mat-icon-button disabled></button>
    {{node.item}}
  </mat-tree-node>

  <mat-tree-node
    *matTreeNodeDef="let node; when: hasChild"
    [style.display]="filterParentNode(node) ? 'none' : 'block'"
    matTreeNodePadding
    matTreeNodePaddingIndent="20"
  >
    <button
      class="button__arrow"
      mat-icon-button
      matTreeNodeToggle
      [attr.aria-label]="'Toggle ' + node.item"
    >
      <mat-icon class="mat-icon-rtl-mirror">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.item}}
  </mat-tree-node>
</mat-tree>

TypeScript File below:

import { SelectionModel } from '@angular/cdk/collections';
import { FlatTreeControl } from '@angular/cdk/tree';
import { Component, Injectable } from '@angular/core';
import {
  MatTreeFlatDataSource,
  MatTreeFlattener,
} from '@angular/material/tree';
import { BehaviorSubject } from 'rxjs';

/**
 * Node for to-do item
 */
export class TodoItemNode {
  children: TodoItemNode[];
  item: string;
}

/** Flat to-do item node with expandable and level information */
export class TodoItemFlatNode {
  item: string;
  level: number;
  expandable: boolean;
}

/**
 * The Json object for to-do list data.
 */
const TREE_DATA = [
  {
    id: 'A',
    friendlyName: 'Account',
    columns: [
      {
        id: 'a1',
        friendlyName: 'Account Code',
      },
      {
        id: 'a2',
        friendlyName: 'Account Value',
      },
    ],
  },
  {
    id: 'C',
    friendlyName: 'Customer',
    columns: [
      {
        id: 'c1',
        friendlyName: 'Customer Code',
      },
      {
        id: 'c2',
        friendlyName: 'Customer Value',
      },
    ],
  },
];

/**
 * Checklist database, it can build a tree structured Json object.
 * Each node in Json object represents a to-do item or a category.
 * If a node is a category, it has children items and new items can be added under the category.
 */
@Injectable()
export class ChecklistDatabase {
  dataChange = new BehaviorSubject<TodoItemNode[]>([]);
  get data(): TodoItemNode[] {
    return this.dataChange.value;
  }

  constructor() {
    this.initialize();
  }

  initialize() {
    // Build the tree nodes from Json object  . The result is a list of `TodoItemNode` with nested
    //     file node as children.
    const data = this.buildFileTree(TREE_DATA, 0);
    console.log(data);
    // Notify the change.
    this.dataChange.next(data);
  }

  /**
   * Build the file structure tree. The `value` is the Json object, or a sub-tree of a Json object.
   * The return value is the list of `TodoItemNode`.
   */
  buildFileTree(obj: { [key: string]: any }, level: number): any[] {
    return Object.keys(obj).reduce<any[]>((accumulator, key) => {
      const value = obj[key];
      const node = new TodoItemNode();
      node.item = key;

      if (value != null) {
        if (typeof value === 'object') {
          node.children = this.buildFileTree(value, level + 1);
        } else {
          node.item = value;
        }
      }

      return accumulator.concat({
        ...node,
        otherInfo: key,
      });
    }, []);
  }

  /** Add an item to to-do list */
  insertItem(parent: TodoItemNode, name: string) {
    if (parent.children) {
      parent.children.push({ item: name } as TodoItemNode);
      this.dataChange.next(this.data);
    }
  }

  updateItem(node: TodoItemNode, name: string) {
    node.item = name;
    this.dataChange.next(this.data);
  }
}

/**
 * @title Tree with checkboxes
 */
@Component({
  selector: 'tree-checklist-example',
  templateUrl: 'tree-checklist-example.html',
  styleUrls: ['tree-checklist-example.css'],
  providers: [ChecklistDatabase],
})
export class TreeChecklistExample {
  /** Map from flat node to nested node. This helps us finding the nested node to be modified */
  flatNodeMap = new Map<TodoItemFlatNode, TodoItemNode>();

  searchString = '';

  /** Map from nested node to flattened node. This helps us to keep the same object for selection */
  nestedNodeMap = new Map<TodoItemNode, TodoItemFlatNode>();

  /** A selected parent node to be inserted */
  selectedParent: TodoItemFlatNode | null = null;

  /** The new item's name */
  newItemName = '';

  treeControl: FlatTreeControl<TodoItemFlatNode>;

  treeFlattener: MatTreeFlattener<TodoItemNode, TodoItemFlatNode>;

  dataSource: MatTreeFlatDataSource<TodoItemNode, TodoItemFlatNode>;

  /** The selection for checklist */
  checklistSelection = new SelectionModel<TodoItemFlatNode>(
    true /* multiple */
  );

  constructor(private _database: ChecklistDatabase) {
    this.treeFlattener = new MatTreeFlattener(
      this.transformer,
      this.getLevel,
      this.isExpandable,
      this.getChildren
    );
    this.treeControl = new FlatTreeControl<TodoItemFlatNode>(
      this.getLevel,
      this.isExpandable
    );
    this.dataSource = new MatTreeFlatDataSource(
      this.treeControl,
      this.treeFlattener
    );

    _database.dataChange.subscribe((data) => {
      this.dataSource.data = data;

      this.treeControl.expand(this.treeControl.dataNodes[0]);
    });
  }

  getLevel = (node: TodoItemFlatNode) => node.level;

  isExpandable = (node: TodoItemFlatNode) => node.expandable;

  getChildren = (node: TodoItemNode): TodoItemNode[] => node.children;

  hasChild = (_: number, _nodeData: TodoItemFlatNode) => _nodeData.expandable;

  hasNoContent = (_: number, _nodeData: TodoItemFlatNode) =>
    _nodeData.item === '';

  /**
   * Transformer to convert nested node to flat node. Record the nodes in maps for later use.
   */
  transformer = (node: TodoItemNode, level: number) => {
    const existingNode = this.nestedNodeMap.get(node);
    const flatNode =
      existingNode && existingNode.item === node.item
        ? existingNode
        : new TodoItemFlatNode();
    flatNode.item = node.item;
    flatNode.level = level;
    flatNode.expandable = !!node.children?.length;
    this.flatNodeMap.set(flatNode, node);
    this.nestedNodeMap.set(node, flatNode);
    return flatNode;
  };

  // search filter logic start
  filterLeafNode(node: TodoItemFlatNode): boolean {
    if (!this.searchString) {
      return false;
    }
    return (
      node.item.toLowerCase().indexOf(this.searchString?.toLowerCase()) === -1
    );
  }

  filterParentNode(node: TodoItemFlatNode): boolean {
    if (
      !this.searchString ||
      node.item.toLowerCase().indexOf(this.searchString?.toLowerCase()) !== -1
    ) {
      return false;
    }
    const descendants = this.treeControl.getDescendants(node);

    if (
      descendants.some(
        (descendantNode) =>
          descendantNode.item
            .toLowerCase()
            .indexOf(this.searchString?.toLowerCase()) !== -1
      )
    ) {
      return false;
    }

    return true;
  }
  // search filter logic end

  /** Whether all the descendants of the node are selected. */
  descendantsAllSelected(node: TodoItemFlatNode): boolean {
    const descendants = this.treeControl.getDescendants(node);
    const descAllSelected =
      descendants.length > 0 &&
      descendants.every((child) => {
        return this.checklistSelection.isSelected(child);
      });
    return descAllSelected;
  }

  /** Whether part of the descendants are selected */
  descendantsPartiallySelected(node: TodoItemFlatNode): boolean {
    const descendants = this.treeControl.getDescendants(node);
    const result = descendants.some((child) =>
      this.checklistSelection.isSelected(child)
    );
    return result && !this.descendantsAllSelected(node);
  }

  /** Toggle the to-do item selection. Select/deselect all the descendants node */
  todoItemSelectionToggle(node: TodoItemFlatNode): void {
    this.checklistSelection.toggle(node);
    const descendants = this.treeControl.getDescendants(node);
    this.checklistSelection.isSelected(node)
      ? this.checklistSelection.select(...descendants)
      : this.checklistSelection.deselect(...descendants);

    // Force update for the parent
    descendants.forEach((child) => this.checklistSelection.isSelected(child));
    this.checkAllParentsSelection(node);
  }

  /** Toggle a leaf to-do item selection. Check all the parents to see if they changed */
  todoLeafItemSelectionToggle(node: TodoItemFlatNode): void {
    this.checklistSelection.toggle(node);
    this.checkAllParentsSelection(node);
  }

  /* Checks all the parents when a leaf node is selected/unselected */
  checkAllParentsSelection(node: TodoItemFlatNode): void {
    let parent: TodoItemFlatNode | null = this.getParentNode(node);
    while (parent) {
      this.checkRootNodeSelection(parent);
      parent = this.getParentNode(parent);
    }
  }

  /** Check root node checked state and change it accordingly */
  checkRootNodeSelection(node: TodoItemFlatNode): void {
    const nodeSelected = this.checklistSelection.isSelected(node);
    const descendants = this.treeControl.getDescendants(node);
    const descAllSelected =
      descendants.length > 0 &&
      descendants.every((child) => {
        return this.checklistSelection.isSelected(child);
      });
    if (nodeSelected && !descAllSelected) {
      this.checklistSelection.deselect(node);
    } else if (!nodeSelected && descAllSelected) {
      this.checklistSelection.select(node);
    }
  }

  /* Get the parent node of a node */
  getParentNode(node: TodoItemFlatNode): TodoItemFlatNode | null {
    const currentLevel = this.getLevel(node);

    if (currentLevel < 1) {
      return null;
    }

    const startIndex = this.treeControl.dataNodes.indexOf(node) - 1;

    for (let i = startIndex; i >= 0; i--) {
      const currentNode = this.treeControl.dataNodes[i];

      if (this.getLevel(currentNode) < currentLevel) {
        return currentNode;
      }
    }
    return null;
  }
}

I am using Angular Material Tree to obtain the tree structure/hierarchical rendering of all the parent and child nodes in the above data.

However, the use case i have in hand is to render only values of only friendlyName key within the final rendering tree.

I need an output something like below:

 // search box here
 v Account
   Account Code
   Account Value
 v Customer
   Customer Code
   Customer Value

Can i get some help to achieve this tree structure?

StackBlitz Below:

https://stackblitz.com/edit/tree-with-checkbox-and-a-filter-3fuz5x?file=src%2Fapp%2Ftree-checklist-example.ts,src%2Fapp%2Fmaterial-module.ts,src%2Fapp%2Ftree-checklist-example.html 

How do I push an event to the GTM datalayer for when a HubSpot form has loaded on my page?

I have created a form listener that is listening for when a form has loaded on the page. This is the script:

<script type="text/javascript">
window.addEventListener('message', function(event) {
   if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
       window.dataLayer.push({
        'event': 'hubspot-form-ready',
        'hs-form-guid': event.data.id
      });
    }
});
</script>

I have a similar script that works for ‘onFormSubmitted’ just fine, but I can’t seem to get anything to work for ‘onFormReady’.

My end goal is to listen for the form to make sure it has loaded on the page, then use that event to manipulate the form (e.g. add cookie values to hidden form fields). I just have to make sure the form is loaded first.

Has anyone done anything similar to this?

cypress actions – initialize component beforeEach hook

I have developed the following code on an index file

    let log = Cypress.log({
        'displayName': 'component',
        'name': name
    });
    cy
        .window({ log: false })
        .then($win => {
            const component = name === 'root' ? $win.app : $win.app.$children.find(e => e.$vnode.tag.includes(name))
            log.set({
                consoleProps: () => {
                    return { component };
                }
            });
            return component;
        });
})

Test are working fine if i use cy.component inside the test (it) but that force me to use it call it lot of times since I have to call it for all test.

I would like to initialize the component only once on a beforeEach hook and then re-use it on each test.

How can I do that?

Thank you all in advance

Can someone explain prototype constructors?

Person.prototype = personPrototype;
Person.prototype.constructor = Person;

I don’t understand these 2 lines of this code.

I understand constructor functions need prototypes so that in this case, every person will have greet() or eat() etc. One master object to rule them all, that makes sense.

What I don’t get is why the prototype needs a constructor, isn’t that what Person() is?

Create a function that takes an object of a fullname and age and returns an object with the name split into first and last name and age [closed]

I want to create a function that takes a full name and an age as an object and returns another object where the name has been split into the first and last names with the age. For example if I were to input {name: “John Smith”, age: “26”} I would like the output to be {firstName: “John”, lastName: “Smith”, age: “26”}. Any hep would be massively appreciated. Thanks 🙂

Functions and scripts refusing to run on website

Recently on the websites i’ve made, i’ve swapped divs around to change the entire screen without relying on an HTML File. I created a JS file with some functions in it to do this for me. When I tried to open the file in chrome, it didn’t run the script. I think there is an error in my code, when I put the code into it’s own script tag and it still didn’t work. I’ve been using a custom Scene tag for this. Here is my javascript:

const sceneElements = document.getElementsByTagName('scene');
var currentScene;

sceneElements.forEach(element => {
  element.style.display = "none";
});

alert('hello');

const getSceneObject = (name) => {
  return document.getElementsByName(name)[0];
}

const getSceneObjectById = id => {
  return document.getElementById(id);
}

const LoadScene = scene => {
  currentScene.style.display = "none";
  currentScene = scene;
  scene.style.display = "none";
}

const setFirstScene = (scene) => {
  currentScene = scene;
  scene.style.display = "block";
}

setFirstScene(getSceneObject('loadingscreen'));
scene {
      margin-left: auto;
      margin-right: auto;
      display: block;
      width: fit-content;
    }
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="SceneManager.js"></script>
  <title>Test Scenes</title>
</head>

<body>
  <scene name="loadingscreen">
    loading screen :0
  </scene>
  <scene name="main">
    <h1>main menu :0</h1>
  </scene>
</body>

</html>

Any help would be appriciated

How to stop an audio element created by a function? IE: audio = new Audio()

I’m creating a Canvas game and I’m using this to stop all audios:

  document.querySelectorAll("audio").forEach((el) => {
  if (
    el.id === "song1" ||
    el.id === "song2" ||
    el.id === "song3"
  ) {
    el.volume = 0;
    el.pause();
  } else {
    el.currentTime = 0;
    el.volume = 0;
    el.pause();
  }
});

The problem I have is that this stop all the audios within the <head></head> tag in the html file (preloaded ones), but it does not work for audios created dinamically

function soundGo(newAudio, boolean) {
  if (boolean === true) {
    let audio = new Audio(newAudio);
    audio.volume = 0.1;
    audio.play();
} else {
    let audio = new Audio(newAudio);
    audio.volume = 0;
    audio.pause();
}
}

I want to know if it’s possible to iterate all the elements created with new Audio(). The querySelectorAll does not the trick, at least in my case (maybe I’m doing it wrong…).

I tried this also:
stop dynamically created Audio

Tailwindcss not rendering in ExpressJS/React app

I am trying to add TailwindCSS to my existing Express JS + React application. I have tried many different tutorials, such as this one https://tailwindcss.com/docs/installation for regular JS, and this one made specifically for Create-React-App https://tailwindcss.com/docs/guides/create-react-app . I later tried this tutorial for express js https://daily.dev/blog/how-to-use-tailwindcss-with-node-js-express-and-pug
My project was initially made with Create-React-App, but I later changed everything to run in Express JS. So I need to build it first before I see any changes. I’ve done that every single time I try something different. I’ve even run the tailwind specific build command every time to see if that does anything but so far nothing. It seems like it doesn’t even render on my plain html page, nevermind my react side.

Here is my project for reference https://github.com/twbluenaxela/LVChineseBusinessCrawler/pull/35

Here is my scripts for package json

"scripts": {
"predeploy": "npm install",
"dev": "react-scripts --openssl-legacy-provider start",
"clientbuild": "npm install && node server/index.js",
"test": "react-scripts test",
"build": "react-scripts --openssl-legacy-provider build",
"build:css": "postcss src/index.css -o dist/output.css",
"eject": "react-scripts eject",
"start_cors": "node cors.js",
"start": "node server/index.js" }

Here’s my post css config js

module.exports = {
  plugins: [require('tailwindcss'), require('autoprefixer')],
}

Here’s my tailwind config

module.exports = {
    content: [
      "./src/**/*.{js,jsx,ts,tsx}",
      "./build/**/*.html"
    ],
    theme: {
      extend: {},
    },
    plugins: [
      {
        tailwindcss: {},
        autoprefixer: {},
      },
    ],
  };

Here’s my link to my dist folder in my index html (location: public/index.html)

    <link href="/dist/output.css" rel="stylesheet">

Here’s my express side. I think it possibly may have to deal with express first loading these ‘chunk’ files generated by running the ‘react-scripts build’ script and then defaulting to that rather than tailwind?

// Have Node serve the files for our built React app
app.use(express.static(path.resolve(__dirname, '../build')));
//this is for tailwind.
app.use(express.static(path.join(__dirname, 'dist')));


// Stop browser from sending requests to get the icon
app.get('../build/favicon.ico', (req, res) => res.status(204).end());

// All other GET requests not handled before will return our React app
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../build/index.html'));
});

// Start the server and listen on the preconfigured port
app.listen(port, () => console.log(`App started on port ${port}.`));

Here’s the log I get from the server when I reload the page

gitpod /workspace/LVChineseBusinessCrawler (NodemonFix) $ npm run start

> [email protected] start
> node server/index.js

App started on port 3001.
GET / 200 3.406 ms - 2371
GET /dist/output.css 200 1.897 ms - 2371
GET /static/css/main.a6b1053c.chunk.css 200 0.556 ms - 108
GET /static/js/2.b2955d3e.chunk.js 200 0.561 ms - 188544
GET /static/js/main.bfafc08b.chunk.js 200 0.453 ms - 2862
GET /static/css/main.a6b1053c.chunk.css.map 200 0.609 ms - 227
GET /favicon.ico 200 0.719 ms - 3870
GET /manifest.json 200 0.401 ms - 319

As you can see it does seem like it knows where my output.css is and I’m assuming it loads it? So maybe its’ the chunk css overwriting it?
So I tested it on my index html in my public folder by changing the h1 heading to this line

    <h1 class="text-3xl font-bold underline">

And it just shows regular h1 without any underline or anything.
Is there something I’m not seeing here? I would realllyyy appreciate any help I could get!!

how does childNode indexing work with javascript?

For example, if I have

              <div>
                <h2>Name</h2>
                <h3>age</h3>
                <span class='fa fa-trash'></span>
             </div>

and when clicking the span (icon) I say

this.parentNode.childNodes[1].innerText

it would target the Name but if I say

this.parentNode.childNodes[2].innerText

it would not target Age. why is this? Is there a resource that explains this well? I know the indexing doesn’t start at 0 but I don’t understand how the indexing work.

Can’t catch error thrown from Node’s built-in function callback

I’ve been studying a lot on asynchronous javascript, from callbacks to promises to async/await.

Now I’m having a hard time understanding why do I lose control over error handling in the following code sample. I’ve even dived into Node’s source code, but that gave me more trouble than answers.

This is what I do:

  1. Inside a global try/catch block, I call Node’s built-in fs.readFile, giving it a callback that just throws an error;
  2. The error isn’t caught, however, and I suppose it somehow bubbles up to the global scope, provoking the JS Engine to emit an uncaughtException event.
const { readFile } = require('node:fs')

process.on('uncaughtExceptionMonitor', (error, origin) => {
  console.log('nuncaughtExceptionMonitor handler: {')
  console.log(`ERROR: ${error}`)
  console.log(`ORIGIN: ${origin}`)
  console.log('}n')
})

try {
  readFile('./jsconfig.json', 'utf8', (err, res) => {
    if (err) console.log('failed to read file')
    if (res) console.log('successfully read file')

    throw new Error(`THROWN BY BUILT-IN FUNCTION'S CALLBACK`) //error thrown
  })
} catch (error) {
  console.log(`error caught by readFile's outer scope`) // not caught here
}

When run, it gives me the following result:

successfully read file

uncaughtExceptionMonitor handler: { ERROR: Error: THROWN BY BUILT-IN
FUNCTION’S CALLBACK ORIGIN: uncaughtException }

C:UsersHeavyDocumentsdevhwoarangleg.js:15
throw new Error(THROWN BY BUILT-IN FUNCTION'S CALLBACK) //error thrown
^

Error: THROWN BY BUILT-IN FUNCTION’S CALLBACK
at C:UsersHeavyDocumentsdevhwoarangleg.js:15:11
at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)

This is my first question so I’m not quite comfortable with Stackoverflow’s formatting. I apologize for that.

Can you help me?

i need help to put 3 boxes in one line

I am working on simple HTML web but I am stuck on something like 3 boxes I want accordingly in one line you can check the screenshot of example for that how I want I tried many times to do by every way but I failed to solve or sort out this issue kindly please help me in that

see this screenshot how it showing

enter image description here

Here is the screenshot of the example

enter image description here

Here is my code:

<div class="property-wrap mb-2 row no-gutter" id="pp">
                            <div class="col-md-4 col-sm-20">
                                <div class="ppt-list list-vw mb-30 featured" style="cursor: pointer" onclick="window.location.href='https://supershop.ng/smart1'">
                                    <figure id="mfs">
                                        <!-- <span class="tag left text-uppercase bg-dark">$5,70,0000</span>
                                        <span class="tag right text-uppercase primary-bg">for rent</span> -->
                                        <a href="https://supershop.ng/smart1" class="image-effect overlay">
                                            <img src="assets/images/smart1-logo.svg" alt="" style="width: 100px; height: 100px; border-radius: 100px;" id="mis">
                                        </a>
                                    </figure>
                                    <!--fig-->

                                    <div class="content" id="mcs">
                                        <h4 class="mb-0"><a href="https://supershop.ng/smart1">SuperShopper</a></h4>
                                        <div class="mb-15"><p>Lekki Phase 1, Lekki</p></div>
                                    </div>
                                    <!--content-->
                                </div>
                            </div>

                            <div class="col-md-4 col-sm-6">
                                <div class="ppt-list list-vw mb-30 featured" style="cursor: pointer" onclick="window.location.href='https://supershop.ng/green_way'">
                                    <figure id="mfs">
                                        <!-- <span class="tag left text-uppercase bg-dark">$5,70,0000</span>
                                        <span class="tag right text-uppercase primary-bg">for rent</span> -->
                                        <a href="https://supershop.ng/green_way" class="image-effect overlay">
                                            <img src="assets/images/green_way.png" alt="" style="width: 100px; height: 100px; border-radius: 100px;" id="mis">
                                        </a>
                                    </figure>
                                    <!--fig-->

                                    <div class="content" id="mcs">
                                        <h4 class="mb-0"><a href="https://supershop.ng/green_way">GreenWay Supermarket</a></h4>
                                        <div class="mb-15"><p>142 Lekki - Epe Expressway, Beside Monarch Event Center, Lekki</p></div>
                                    </div>
                                    <!--content-->
                                </div>
                            </div>

                            <div class="col-md-4 col-sm-6">
                                <div class="ppt-list list-vw mb-30 featured" style="cursor: pointer" onclick="window.location.href='https://supershop.ng/pjv1'">
                                    <figure id="mfs">
                                        <!-- <span class="tag left text-uppercase bg-dark">$5,70,0000</span>
                                        <span class="tag right text-uppercase bg-blue">for sale</span> -->
                                        <a href="#" class="image-effect overlay">
                                            <img src="assets/images/pjv.png" alt="" style="width: 100px; height: 100px; border-radius: 0px;" id="mis">
                                        </a>
                                    </figure>
                                    <!--fig-->

                                    <div class="content" id="mcs">
                                        <h4 class="mb-0"><a href="https://supershop.ng/pjv1">PJV Supermarket</a></h4>
                                        <div class="mb-15"><p>36b Kusenla Road, Ikate Elegushi, Lekki</p></div>
                                        <!--content-->

                                    </div>
                                    <!--content-->


                                </div>
                            </div>

How do i fix this code to only check for strings that are 4 charachters of length (sorry for the commented lines)?

The code underneath is meant to look trough Strings that have the same hashvalue as “golf” yet it starts at 1 charachter, then goes up to 2, then 3 and then 4… I want the code to start at 4 instead of going up trough 1 tot 3.

The reason I want this is because I want to use this code to find hashes of stringlength 10+… it would take too much time to go trough 1 to 9 stringlengths.

const fs = require('fs')

hashCode = function(s) {
  var h= 0, l = s.length, i = 0;
  if ( l > 0 )
    while (i<l)
      h = (h << 5) - h + s.charCodeAt(i++) | 0;
  return h;
}

var crackableSeedInt = hashCode("golf")
    // Javascript program for the above approach
  //
    // Function to generate permutations of
    // at most X elements from array arr[]
    function differentFlagPermutations(X, arr)
    {
    let ml = [];
    ml = arr;
    for(let i = 0; i < ml.length; i++)
    {
    //console.log(ml[i] + " ")
        //document.write(ml[i] + " ");
    }
  let count2 = 0
    let count = ml.length;

    // Traverse all possible lengths
    for(var z = 0; z < X - 1; z++)
    {

        // Stores all combinations
        // of length z
        let tmp = [];

        // Traverse the array
        for(let i = 0; i < arr.length; i++)
        {
        for(let k = 0; k < ml.length; k++)
        {
            if (arr[i] != ml[k])
            {

            // Generate all
            // combinations of length z
            tmp.push(ml[k] + arr[i]);
            count += 1;
            }
        }
        }

        // Print all combinations of length z
        for(let i = 0; i < tmp.length; i++)
        {
      //console.log(tmp[i] + " ")
      var testInt = hashCode(tmp[i])
      count2 += 1
      var length = tmp[i].length
      console.log(count2 + " > " + length + " > " + tmp[i] + ' > ' + testInt)
      if (crackableSeedInt == testInt) {
        var data = String(tmp[i] + ' > ' + crackableSeedInt + ' > ' + testInt + "n")
        fs.appendFileSync('Output.txt', data, (err) => {
          console.log(err)

          // In case of a error throw err.
        if (err) throw err;
      })

      }

        //document.write(tmp[i] + " ");
        }

        // Replace all combinations of length z - 1
        // with all combinations of length z
        ml = tmp;
    }
    }

    // Given array

  //let arr = [" ","=","&",".","z","y","x","w","v","u","t","s","r","q","p","o","n","m","l","k","j","i","h","g","f","e","d","c","b","a"]
  //let arr = ["b","a"]
    let arr = ["a","b","c","d","e","f","g","h","i","j","k","l","m","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","&","="," "];

    // Given X
    let X = 4;

    differentFlagPermutations(X, arr);


// count += 1
// var testInt = hashCode(randomstring)
// console.log(count + ' > ' + randomstring + ' > ' + testInt)
// if (crackableSeedInt == testInt) {
//   console.log("Found a seed")
//   var data = String(tmp[i] + ' > ' + crackableSeedInt + ' > ' + testInt + "n")
//   fs.appendFileSync('Output.txt', data, (err) => {
//     console.log(err)
//
//     // In case of a error throw err.
//     if (err) throw err;
//   })
// }
//setInterval(differentFlagPermutations,0)

Determine when jzip async function is complete

How can I let spellcheckePub() know when gatherWords() is fully done executing? gatherWords() is processing epub books so it takes a while and when I console.log(words) it is empty, presumably because the forEach hasn’t completed yet.

 function spellcheckePub() {
      gatherWords();
      console.log(words);
      // do stuff with words
 }

    function gatherWords() {
      words = [];
      masterePub.forEach(function (relativePath, file) {
        if (!file.dir) {
          masterePub.file(file.name).async("text")
          .then(function success(content) {
            //make an array of words
            content = content.split(/s+/);
            words = words.concat(content);
          });
        }
      });
    } // end spellcheckePub function