Shortcut version getting some object values into array in certain order?

I have object with many keys, I want to get some of corresponding values into array, in certain order.

To get these values I can use deconstruction like

const obj = { foo: 1, bar: 3, baz: 2, other: 666, keys: "here" };
const { foo, bar, baz } = obj;
const array = [ foo, bar, baz ]; // 1, 3, 2

Of course, I can use many ways to achieve my goal, like without deconstruction:

const array = [ obj.foo, obj.bar, obj.baz ]; // 1, 3, 2

Or having these keys as an array and mapping over it.

const array = ["foo", "bar", "baz"].map( v => obj[v] )

But is there some simpler way?

In Perl, for example, is simple shortcut:

my %obj = (foo => 1, baz => 3, bar => 2); 
my @arr = @obj{ ('foo','bar','baz') }; # 1, 3, 2

And instead ('foo','bar','baz') here I can actually use any statement which returns list of these keys as selector for object (hash).

I can’t figure out something similar in JS.

Google Places API returns diferent street number which was given in auto complete

Something wierd starts to happens with Google Places API. I am working on a Python Django app but Google Places API is returning diferent street number in it queries.

I search a street name and number “Rua Augusta, 300”:
enter image description here

But after selecting it the response cames with other number options instead of the choosen one.
enter image description here

Does anyone knows what could be happening? It does happens with other addresses even where I live in. đŸ™‚
enter image description here

Thank you very much!

[Error: Invalid URL (POST /v1/chat/completions/)]: React Native/ChatGPT API in Android problem

I’m building a simple ChatGPT API connection on React Native using Expo, and when i run the app in web browser there’s no problem, problem comes when i run it on Android via Expo Go, i got this error:
[Error: Invalid URL (POST /v1/chat/completions/)]

Error at running React Native App in Android with Expo Go

App running on Web

I don’t know if this is related but i got this error when running on web (it’s still working)

Error when running App on Web Browser

This is the source code of the connection:

import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet, Alert } from 'react-native';
import OpenAI from "openai";
import theme from '../theme';

const ChatGPT = () => {

    const openai = new OpenAI({
        apiKey: (here goes my api key),
        dangerouslyAllowBrowser: true
    });
    
    
  const [input, setInput] = useState('');
  const [messages, setMessages] = useState([]);

  const sendMessage = async () => {
    if (!input) return;
  
    // Send the user's message to the ChatGPT API
    try {
      const response = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [
          {
            "role": "user",
            "content": input
          },
        ],
        temperature: 1,
        max_tokens: 256,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0,
      });
      console.log(response);
      setMessages([...messages, { text: input, user: true }, { text: response.choices[0].message.content, user: false }]);
      setInput('');
    } catch (error) {
      console.log(error)
    }
    
    
    // Add the user's message and the AI's response to the chat
    
  };

  return (
    <View style={{marginTop: 40}}>
      <View>
        {
          //Adds the message
        messages.map((message, index) => (
          <View style>
            <Text key={index} style={styles.chatContainer}>
              {message.text}
            </Text>
          </View>
          
        ))}
      </View>
      <View>
        <TextInput
          value={input}
          onChangeText={setInput}
          placeholder="Escriba su consulta..."
        />
        <Button title="Send" onPress={sendMessage} />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
    chatContainer: {
      flex: 1,
      backgroundColor: theme.colors.backgroundPrimary,
      alignItems: 'center',
      justifyContent: 'center',
      color: theme.colors.textPrimary
    },
    text: {
        color: "#fff"
    }
  });

export default ChatGPT;

and if needed, this is my package.json:

{
  "name": "pisapp-app",
  "version": "1.0.0",
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "@expo/webpack-config": "^19.0.0",
    "@react-navigation/drawer": "^6.6.3",
    "@react-navigation/native": "^6.1.7",
    "@react-navigation/native-stack": "^6.9.13",
    "@react-navigation/stack": "^6.3.17",
    "@types/react": "~18.2.14",
    "axios": "^1.5.0",
    "dotenv": "^16.3.1",
    "expo": "~49.0.8",
    "expo-status-bar": "~1.6.0",
    "firebase": "^10.4.0",
    "openai": "^4.4.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.72.4",
    "react-native-gesture-handler": "~2.12.0",
    "react-native-reanimated": "~3.3.0",
    "react-native-safe-area-context": "4.6.3",
    "react-native-screens": "~3.22.0",
    "react-native-web": "~0.19.6",
    "typescript": "^5.1.3"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@babel/plugin-transform-export-namespace-from": "^7.22.11",
    "babel-eslint": "^10.1.0",
    "eslint-config-standard": "^17.1.0",
    "eslint-config-standard-jsx": "^11.0.0",
    "eslint-config-standard-react": "^13.0.0",
    "eslint-plugin-import": "^2.28.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-react": "^7.33.2"
  },
  "private": true,
  "eslintConfig": {
    "parser": "babel-eslint",
    "extends": [
      "standard",
      "standard-jsx",
      "standard-react"
    ]
  }
}

I tried clearing cache, even changing the chatGPT API model, but with no results.

Dynamically passing value to .click event Jquery

I am getting the values of a CSS class using Jquery. When I click the header, I want all of the radio boxes to be marked as checked.
I loop through and find the values, using console.log to check if I am returning the correct values which I am. However when I try to use the function, it will only run it correctly on the first element in the array, where I would like it to apply to all names found in the loop.

var skil = $('.Routes');
var skills = new Array();
skil.each(function(i) {
  skills.push($(this).text());
  var Route = '#'+skills[i].replaceAll(' ','');
  console.log(Route);
   $(Route).on('click', function() {
    $(Route).prop("checked", true); //This only performs the function on the First value (in this case for "Purchased")
   });
});

Below is an extract of code which runs correctly on both headers. I could replicate this, but there are 17 classes, so ideally I would like to dynamically pass the value in and run through one function if possible.

$('#Purchased').on('click', function() {
    $('.Purchased').prop("checked", true);
});

$('#AnglePlant').on('click', function() {
    $('.Angle_Plant').prop("checked", true);
});

See HTML to build table below

<th class="rotate"><div><span class ="Routes" id ="Purchased"> Purchased</span></div></th>
    <th class="rotate"><div><span class ="Routes" id ="Angle_Plant"> Angle Plant</span></div></th>

<td bgcolor="#8DB255" class=""> <input type="radio" class="get_value Purchased" name="48215:4G1" id="r8215:4201" value="4:716:597:18.25:200:0:200:NA:PBJB_18223_JTC:375:8215:4:20:2023/09/13:284:284:284:284:284:0::0" checked=""></td>
    <td bgcolor="#8DB255" class=""> <input type="radio" class="get_value Angle_Plant" name="48215:4G1" id="r8215:4201" value="4:716:597:18.25:200:0:200:NA:PBJB_18223_JTC:375:8215:4:20:2023/09/13:284:284:284:284:284:0::0" checked=""></td>

Is this Front-end or Back-end? [closed]

Front end developers are someone who codes the look and feel of a web app right? For example, styling the button.

So… what is the specific role or position of someone who still codes the look and feel of the web app, but is more focused on what will happen when that button clicks? For example, fetching, communicating with the database by updating or deleting things, routing, complex stage management, syncing data to the ui: showing and what not to show to users, etc.?

How to center my text in a cell using JS pdf

I am trying to centre the text in my PDF within the cells both in the x and in the y.
In the code below the Y centring seems to be sorted but the x is slightly off

    const doc = new jsPDF();

    const headers: any = [{title: 'Date', width: 15, border: 'TRL'},
      {title: 'Departure', width: 30, border: 'TRL'},
      {title: 'Arrival', width: 30, border: 'TRL'},
      {title: 'ASFVDSDD', width: 70, border: 'TRL'},
      {title: '', width: 15, border: 'TRL'},
      {title: '', width: 15, border: 'TRL'},
      {title: '', width: 15, border: 'TRL'},
      {title: '', width: 15, border: 'TRL'},
      {title: '', width: 25, border: 'TRL'},
      {title: 'T Offs', width: 20, border: 'TRL'},
      {title: 'Landings', width: 20, border: 'TRL'}]
    ;

    const margin = {top: 10, right: 10, bottom: 10, left: 10};
    let currentX: any = margin.left;
    let currentY = margin.top;
    doc.setFontSize(7);
    doc.addPage("", "l");
    headers.forEach((header: any, index: any) => {
      const colWidth = header.width;
      const fontSize = 7; // Default font size
      const textWidth = doc.getStringUnitWidth(header.title) * fontSize;
      const cellHeight = fontSize; // Adjust as needed
      const cellPadding = 0; // Adjust as needed

      const textX = currentX + (colWidth / 2);

      const textY = currentY;

      doc.setFontSize(fontSize);

      doc.setLineWidth(0.1);
      doc.rect(currentX, currentY, colWidth, cellHeight, 'S');
      doc.text(header.title, textX, currentY + (cellHeight / 2) + 1);

      currentX += colWidth;
    });
    doc.save('auto_sized_table_example.pdf');

Appreciate the help.

Thanks

Track PAGE A AND PAGE B WITH BREVO

I was wondering if someone could give me a hint with this small issue.

I run multiple ads campaigns and i want to be able to track successfull purchases on different pages.

Scenario:

MAIL > PAGE A (LANDING PAGE) > NEW URL TO OFFER SHOP

How can i successfully transfer BREVO tracking values from page A to page B (different website). To be able to recongnize users.

Please note that both pages have brevo tracking code installed.

I expect to get the same values from page a in page b

Moving geometries along path distorting path shape

I am working with the OGL framework and using a looping path to move sphere geometries along it.

The movement starts off well, but slowly morphs the path shape in to a circle. There is a lerp function in the requestAnimationFrame, but looks like each sphere is moving only a percentage towards the +1 index before changing to the one after that, i.e. +2 and so on.

Why is this happening?

Sandbox link: https://codesandbox.io/s/cool-shirley-wddd8v

import { Renderer, Camera, Orbit, Transform, Program, Mesh, Sphere, Polyline, Vec3, Color, Path } from 'https://unpkg.com/ogl';

const vertex = /* glsl */ `
attribute vec3 position;
attribute vec3 normal;

uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform mat3 normalMatrix;

varying vec3 vNormal;

void main() {
    vNormal = normalize(normalMatrix * normal);
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}`;

const fragmentColor = /* glsl */ `
precision highp float;
varying vec3 vNormal;

void main() {
    vec3 normal = normalize(vNormal);
    float lighting = dot(normal, normalize(vec3(-0.3, 0.8, 0.6)));
    gl_FragColor.rgb = vec3(0.24, 0.84, 1.0) + lighting * 0.1;
    gl_FragColor.a = 1.0;
}`;


const renderer = new Renderer({ dpr: 2 });
const gl = renderer.gl;
document.body.appendChild(gl.canvas);
gl.clearColor(.1, .1, .1, 1);

const camera = new Camera(gl, { fov: 75 });
camera.position.set(0, 0, 2);

const controls = new Orbit(camera, {
    target: new Vec3(0, 0, 0)
});

function resize() {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.perspective({ aspect: gl.canvas.width / gl.canvas.height });
}
window.addEventListener('resize', resize, false);
resize();

const scene = new Transform();

const sphereGeom = new Sphere(gl);
const sphereProg = new Program(gl, { vertex, fragment: fragmentColor });

// First three is for moveTo command, rest for bezierCurveTo command
const pathCoords = [-1.0, 0.0, 0.0, -0.9368709325790405, 0.1762027144432068, 0.04529910162091255, -0.7061498761177063, 0.089231938123703, 0.19381383061408997, -0.6332840919494629, 0.2674865424633026, 0.1930660903453827, -0.5615311861038208, 0.4430185854434967, 0.1923297792673111, -0.7734173536300659, 0.5522762537002563, 0.08718681335449219, -0.7070468664169312, 0.7070468664169312, 0.0, -0.6498651504516602, 0.8403899073600769, -0.07511603832244873, -0.5399253368377686, 0.8584117889404297, -0.16668838262557983, -0.38917776942253113, 0.921392560005188, -0.1677459478378296, -0.23391252756118774, 0.9862607717514038, -0.16883520781993866, -0.14611071348190308, 1.0727460384368896, -0.04093937203288078, 0.0, 1.0, 0.0, 0.1674281358718872, 0.9166403412818909, 0.046912387013435364, 0.07777689397335052, 0.6478093862533569, -0.06732462346553802, 0.2400655597448349, 0.5683639645576477, 0.0, 0.4298238456249237, 0.4754713177680969, 0.07872024923563004, 0.49316900968551636, 0.7766210436820984, 0.32597726583480835, 0.7070468664169312, 0.7070468664169312, 0.3101717531681061, 0.8896822333335876, 0.647635817527771, 0.29667505621910095, 0.8556811809539795, 0.5579423308372498, 0.06533028930425644, 0.921392560005188, 0.38917776942253113, 0.0, 0.9742976427078247, 0.2533031702041626, -0.05259828269481659, 1.0508142709732056, 0.14183028042316437, -0.036462459713220596, 1.0, 0.0, 0.0, 0.9368709325790405, -0.1762027144432068, 0.04529910162091255, 0.7061498761177063, -0.089231938123703, 0.19381383061408997, 0.6332840919494629, -0.2674865424633026, 0.1930660903453827, 0.5615311861038208, -0.4430185854434967, 0.1923297792673111, 0.7734173536300659, -0.5522762537002563, 0.08718681335449219, 0.7070468664169312, -0.7070468664169312, 0.0, 0.6498651504516602, -0.8403899073600769, -0.07511603832244873, 0.5399253368377686, -0.8584117889404297, -0.16668838262557983, 0.38917776942253113, -0.921392560005188, -0.1677459478378296, 0.23391252756118774, -0.9862607717514038, -0.16883520781993866, 0.14611071348190308, -1.0727460384368896, -0.04093937203288078, 0.0, -1.0, 0.0, -0.1674281358718872, -0.9166403412818909, 0.046912387013435364, -0.07777689397335052, -0.6478093862533569, -0.06732462346553802, -0.2400655597448349, -0.5683639645576477, 0.0, -0.4298238456249237, -0.4754713177680969, 0.07872024923563004, -0.49316900968551636, -0.7766210436820984, 0.32597726583480835, -0.7070468664169312, -0.7070468664169312, 0.3101717531681061, -0.8896822333335876, -0.647635817527771, 0.29667505621910095, -0.8556811809539795, -0.5579423308372498, 0.06533028930425644, -0.921392560005188, -0.38917776942253113, 0.0, -0.9742976427078247, -0.2533031702041626, -0.05259828269481659, -1.0508142709732056, -0.14183028042316437, -0.036462459713220596, -1.0, 0.0, 0.0];

// Constructing path from cubic Bezier segments.
// Also available `quadraticCurveTo` and `lineTo` commands
const path = new Path();
path.moveTo(new Vec3(pathCoords[0], pathCoords[1], pathCoords[2]));
for (let i = 3; i < pathCoords.length; i += 9) {
    const cp1 = new Vec3(pathCoords[i + 0], pathCoords[i + 1], pathCoords[i + 2]);
    const cp2 = new Vec3(pathCoords[i + 3], pathCoords[i + 4], pathCoords[i + 5]);
    const p = new Vec3(pathCoords[i + 6], pathCoords[i + 7], pathCoords[i + 8]);
    path.bezierCurveTo(cp1, cp2, p);
}

const pathSubdivisions = 256;
const points = path.getPoints(pathSubdivisions);

let spheres = [];

for (let i = 0; i < points.length - 1; i++) {
    const point = points[i];

    const sphere = new Mesh(gl, { 
        geometry: sphereGeom, 
        program: sphereProg 
    });
    sphere.scale.set(0.006);
    sphere.position = point;
    sphere.setParent(scene);
    spheres.push(sphere);
}


function update(now) {
    const progress = (now * 0.00001) % 1;

    // take current Frenet frame
    const frameIndex = Math.floor(progress * pathSubdivisions);
    const frameProgress = progress * pathSubdivisions % 1;

    spheres.forEach((sphere, idx) => {
        let nextIdx = (idx + 1) % (points.length -1 );
        sphere.position
        .copy(points[idx])
        .lerp(points[nextIdx], 0.06);
    })
    
    renderer.render({ scene, camera });
    controls.update();
    requestAnimationFrame(update);
}

requestAnimationFrame(update);

How to clear and fields as using a button?

I’ve been developing a website for the past three weeks using HTML, CSS, and currently JavaScript for a school project. On the “Contact Us” page, I have a “form” (not defined as a form in code) where the user can leave their name, email address, phone number, and description. It looks like this:
enter image description here

The issue that I’m having is that when the user clicks the “Submit” button the four fields are supposed to clear the user’s values and the placeholder text would reappear. So far, my code doesn’t meet this requirement. The only thing that clears the four fields is when the user clicks the “Contact Us” link at the top right of the page. Currently, this is what I have:

<input type="button" value="Submit" onclick="Submit_Form()" />
function Submit_Form() {
  document.getElementByID("Name").value = "";
  document.getElementByID("Email").value = "";
  document.getElementByID("Phone-Number").value = "";
  document.getElementByID("Text-Box").value = "";
}

Here is a more detailed example of my existing code: https://jsfiddle.net/Halomationdude14/pmhbxnjk/6/

I have tried a few different things to resolve this issue that I’ve learned so far such as:

  1. Using the “onload” feature on the containing <div> that encases the form.

  2. Using a <button></button> instead of input.

  3. Using an event listener on the button (with an associated ID) instead of “onclick”.

Aside from what I’ve read in my textbook, most of what I know about JavaScript has been learned from questions on this website. I have tried to format my code to how most people write theirs as seen throughout the Stack Overflow website but nothing has worked so far.

Debounce in ReactJS

I am trying to implement debounce in my search input in React. The below code is causing the delay but its firing the same number of times.

Example – If I type abcd in less than 2 seconds(delay) my debounced value should be abcd instead I am getting console with all values-

Debounced: a 
Debounced: ab 
Debounced: abc 
Debounced: abcd 

What I am assuming, if I type abcd then it should make a single call instead of 4 in this case.

Code –

import { useState } from 'react';

function debounce(cb, delay) {
  let timeoutId;
  return function (...args) {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(() => {
      cb(...args);
    }, delay);
  };
}

export default function App() {
  const [searchVal, setSearchVal] = useState('');
  const [debounceVal, setDebounceVal] = useState('');

  const debouncedChange = debounce((inputValue) => {
    console.log('Debounced:', inputValue);
    setDebounceVal(inputValue);
  }, 2000);

  const handleChange = (e) => {
    const inputValue = e.target.value;
    setSearchVal(inputValue);
    debouncedChange(inputValue);
  };

  return (
    <div className="App">
      <h1>Debounce</h1>

      <div className="container">
        <div className="search-input">
          <input type="text" value={searchVal} onChange={handleChange} />
        </div>

        <div className="search-data">{debounceVal}</div>
      </div>
    </div>
  );
}

Let me know if I am doing something wrong here with the code or my understanding around debounce.

d3js bar chart: panning and zooming to specific values

I want to pan and zoom to a specific area of this bar chart using values from x axis (note, I still want to be able to zoom out/in and pan, so I can’t just recreate the chart with the sliced data)

Here’s my bar (waterfall) chart:

const data = Array.from({ length: 20 }, (_, i) => ({
    letter: i + 1,
    frequency: Math.random()
}));

// Specify the chart’s dimensions.
const width = 928;
const height = 500;
const marginTop = 20;
const marginRight = 0;
const marginBottom = 30;
const marginLeft = 40;

// Create the horizontal scale and its axis generator.
const x = d3.scaleBand()
.domain(data.map(d => d.letter))
.range([marginLeft, width - marginRight])
.padding(.1);

const xAxis = d3.axisBottom(x).tickSizeOuter(0);

// Create the vertical scale.
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.frequency)]).nice()
.range([height - marginBottom, marginTop]);

// Create the SVG container and call the zoom behavior.
const svg = d3.select(`body`).append('svg')
.attr("viewBox", [0, 0, width, height])
.attr("width", width)
.attr("height", height)
.attr("style", "max-width: 100%; height: auto;")
.call(zoom);

// Append the bars.
svg.append("g")
    .attr("class", "bars")
    .selectAll("rect")
    .data(data)
    .join("rect")
    .attr("x", d => x(d.letter))
    .attr("y", (d, i) => {
    if (i === 0) {
        return y(d.frequency); // Start the first bar at the baseline.
    } else {
        const previousY = y(data[i - 1].frequency); // Get the previous bar's y-position.
        const currentY = y(d.frequency); // Get the current bar's y-position.
        return previousY < currentY ? previousY : currentY; // Choose the lower of the two.
    }
})
    .attr("height", (d, i) => {
    if (i === 0) {
        return y(0) - y(d.frequency);
    } else {
        const previousY = y(data[i - 1].frequency); // Get the previous bar's y-position.
        const currentY = y(d.frequency); // Get the current bar's y-position.
        return Math.abs(currentY - previousY); // Calculate the height difference.
    }
})
    .attr("width", x.bandwidth())
    .attr("class", (d, i) => {
    if (i === 0) {
        return "up"; // No class for the first bar.
    } else {
        const previousY = y(data[i - 1].frequency); // Get the previous bar's y-position.
        const currentY = y(d.frequency); // Get the current bar's y-position.
        return previousY < currentY ? "down" : "up"; // Add "up" or "down" class.
    }
});

// Append the axes.
svg.append("g")
    .attr("class", "x-axis")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(xAxis);

svg.append("g")
    .attr("class", "y-axis")
    .attr("transform", `translate(${marginLeft},0)`)
    .call(d3.axisLeft(y))
    .call(g => g.select(".domain").remove());

function zoom(svg) {
    const extent = [[marginLeft, marginTop], [width - marginRight, height - marginTop]];

    svg.call(d3.zoom()
             .scaleExtent([1, 5])
             .translateExtent(extent)
             .extent(extent)
             .on("zoom", zoomed));

    function zoomed(event) {
        x.range([marginLeft, width - marginRight].map(d => event.transform.applyX(d)));
        svg.selectAll(".bars rect").attr("x", d => x(d.letter)).attr("width", x.bandwidth());
        svg.selectAll(".x-axis").call(xAxis);
    }
}

Here’s a JSBIN of this: https://jsbin.com/gubuwogobe/edit?js,output

I think the best way to do this is to create a zoomPanTo() function that takes two parameters:

  1. Start value of the x axis
  2. End value of the x axis

Here’s what I’ve tried:

function zoomPanTo(startX, endX) {
    const newDomain = [startX, endX];
    
    svg.transition().duration(750)
        .call(zoom.transform, d3.zoomIdentity.scale(width / (newDomain[1] - newDomain[0]))
            .translate(-newDomain[0], 0));
}

zoomPanTo('5', '10');

Unfortunately this doesn’t work, and I’m a bit stumped how I can get this working.

randomULID(). Cannot get it to work in TypeScript. Why? [closed]

Really having a hard time getting this to work in Type Script. It works great in JavaScript as you can see but not in TypeScript.

TypesScript Example:

type Base32Char =
  | "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
  | "A" | "B" | "C" | "D" | "E" | "F" | "G"
  | "H" | "J" | "K" | "M" | "N" | "P" | "Q"
  | "R" | "S" | "T" | "V" | "W" | "X" | "Y"
  | "Z";

let lastTime: BigInt = BigInt(0);
let lastRandom: BigInt = BigInt(0);
let counter: BigInt = BigInt(0);

const encodeBase32 = (number: BigInt, length: number): string => {
  const characters: Base32Char[] = [
    "0","1","2","3","4","5","6","7","8","9",
    "A","B","C","D","E","F","G",
    "H","J","K","M","N","P","Q",
    "R","S","T","V","W","X","Y",
    "Z",
  ];
  let result = "";
  while (number > 0n) {
    result = characters[Number(number % 32n)] + result;
    number >>= 5n;
  }
  return result.padStart(length, "0");
};

async function randomULID(): Promise<string> {
  const currentTime: BigInt = BigInt(Date.now()) & 0xFFFFFFFFFFFFn;

  if (currentTime === lastTime) {
    counter++;
    if (counter > 0xFFFFFFFFFFFFn) {
      // Wait for next millisecond for monotonicity
      while (BigInt(Date.now()) <= lastTime) {}
      counter = 0n;
      lastTime = BigInt(Date.now()) & 0xFFFFFFFFFFFFn;
    }
  } else {
    counter = 0n;
    const randomBuffer: Uint8Array = new Uint8Array(10);
    window.crypto.getRandomValues(randomBuffer);
    lastRandom = BigInt(0);
    for (const byte of randomBuffer) {
      lastRandom = (lastRandom << 8n) | BigInt(byte);
    }
  }

  lastTime = currentTime;

  const timeStr: string = encodeBase32(currentTime, 10);
  const randStr: string = encodeBase32(lastRandom + counter, 16);

  return (timeStr + randStr).toUpperCase();
}


// RUN deno run ulid.ts
const ulid = await randomULID();
console.log(ulid);

TypeScript Errors @ https://www.typescriptlang.org/play

Operator '>' cannot be applied to types 'BigInt' and 'bigint'.
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
Operator '%' cannot be applied to types 'BigInt' and 'bigint'.
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
Operator '>>=' cannot be applied to types 'BigInt' and 'bigint'.
An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.
Operator '>' cannot be applied to types 'BigInt' and 'bigint'.
Operator '<=' cannot be applied to types 'bigint' and 'BigInt'.
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
Operator '<<' cannot be applied to types 'BigInt' and 'bigint'.
Operator '+' cannot be applied to types 'BigInt' and 'BigInt'.

JavaScript Example:

Meets all requirements of ULID Specifications in 57 lines of code such as:

  • 48-bit Timestamp: Correctly truncates the timestamp to 48 bits using & 0xFFFFFFFFFFFFn.
  • Base32 Encoding: The encodeBase32 function correctly encodes a BigInt into a Base32 string.
  • Randomness: Uses window.crypto.getRandomValues to generate a cryptographically secure random number.
  • Length: The final ULID string is 26 characters long, which is compliant with the ULID spec.
  • Case: The ULID is returned in uppercase, which is allowed by the specification.
  • Character Set: Defined the Base32 character set in accordance with the ULID spec.
"use strict";
let lastTime = BigInt(0);
let lastRandom = BigInt(0);
let counter = BigInt(0);
const encodeBase32 = (number, length) => {
  const characters = [
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    "A", "B", "C", "D", "E", "F", "G",
    "H", "J", "K", "M", "N", "P", "Q",
    "R", "S", "T", "V", "W", "X", "Y",
    "Z",
  ];
  let result = "";
  while (number > 0n) {
    result = characters[Number(number % 32n)] + result;
    number >>= 5n;
  }
  return result.padStart(length, "0");
};
async function randomULID() {
  const currentTime = BigInt(Date.now()) & 0xffffffffffffn;
  if (currentTime === lastTime) {
    counter++;
    if (counter > 0xffffffffffffn) {
      // Wait for next millisecond for monotonicity
      while (BigInt(Date.now()) <= lastTime) {}
      counter = 0n;
      lastTime = BigInt(Date.now()) & 0xffffffffffffn;
    }
  } else {
    counter = 0n;
    const randomBuffer = new Uint8Array(10);
    window.crypto.getRandomValues(randomBuffer);
    lastRandom = BigInt(0);
    for (const byte of randomBuffer) {
      lastRandom = (lastRandom << 8n) | BigInt(byte);
    }
  }
  lastTime = currentTime;
  const timeStr = encodeBase32(currentTime, 10);
  const randStr = encodeBase32(lastRandom + counter, 16);
  return (timeStr + randStr).toUpperCase();
}

randomULID().then(ulid => console.log("ULID:", ulid));

using wait() to capitalize letters in Javascript in a simple way [duplicate]

<!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">
    <title>Document</title>
</head>
<body>
    <p id="test1">a</p>
    <p id="test2">b</p>
<script>
document.getElementById("test1").innerHTML = "A";
wait(3000);
document.getElementById("test2").innerHTML = "B";
    </script>
</body>
</html>

How does wait() work in Javascript? Does it not just pause a programme. The above code should capitalize the ‘a’ and wait 3 seconds then do the same to the ‘b’.

Prevent Link from activating on click on card icon in React

I have a card wrapped in a Link from the react-router-dom@v5. Inside the Link is a div for the card and the div is positioned relatively. Inside the card div is an icon positioned absolutely to the card that when clicked should change background color. The problem now is that clicking on the icon also clicks the Link which I don’t want. I tried to use e.preventDefault() but it also stops all subsequent events from firing again properly as I want to be able to flip the background color of the icon any time I click on it. I tried e.stopPropagation() and e.nativeEvent.stopImmediatePropagation but they don’t seem to work.

I have also gone through several SO answers but none seem to fix my problem.


 function handleFavClick(event) {
    event.stopPropagation();
    console.log(event);
 }

 <Link to={`/movies/${movie.id}`} key={movie.id}>

      <div 
        className="card"
        key={movie.id}
      >
        <img 
          src="/heart-icon.png"
          alt="heart icon"
          onClick={handleFavClick}
        />
        <img 
          src="/card-image.png"
          alt="original card image"

        />
      </div>  
 </Link>

What could be the issue?

How to embed Swiper styles in main CSS file built by Vite?

I’m working with a classic multi-page Laravel project using SASS and Javascript modules and I’m using Vite to build CSS and JS files. After compiling, a single CSS, and a single JS file created.
Yesterday I installed Swiper JS package and imported it in one of my JS modules as specified on Swiper Getting Started page:

// home.js

import Swiper from 'swiper';
import { Navigation, Pagination } from 'swiper/modules';

import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';

// init Swiper:
export const swiper = new Swiper('.swiper', {
    ...
});

But after compiling, I found that a second separate CSS file containing Swiper styles is built by Vite.
Then, I tried to import Swiper SCSS into my SCSS from node_modules folder:

// _swiper.scss

@import 'swiper/swiper';
@import 'swiper/modules/navigation';
@import 'swiper/modules/pagination';

The styles imported fine but after removing the import directives from the home.js above, Vite stops working with the following error:

Error: Missing "./swiper" specifier in "swiper" package

What I have to do to put Swiper styles into my main CCS file without created another file?