Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Capri Sun Tzu
Oct 24, 2017

by Reene
LINQ is by far my favorite thing in any language and I would give both my nuts to see a native JS implementation

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Capri Sun Tzu posted:

LINQ is by far my favorite thing in any language and I would give both my nuts to see a native JS implementation

Technically, that JS port is exactly as native as the original :v:

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Is there a good way to share Tampermonkey scripts in a small group? I made one to stuff data in a UI in an internal application I had to test a lot over the last couple weeks and I figure others around here might benefit, but I don't want to distribute it outside the office.

Roadie
Jun 30, 2013

porksmash posted:

Is there any sort of advanced object filtering library I can leverage instead of rolling my own? I have to implement something on the level of Newegg's Power Search, but also with user selectable comparisons or value ranges, dates and date ranges. I basically want the ability to dynamically generate SQL WHERE clauses and run it against an array of objects.

If you're doing it all client-side, I'd just use lodash/fp.

porksmash
Sep 30, 2008

Roadie posted:

If you're doing it all client-side, I'd just use lodash/fp.

I am indeed doing it all client side. My research so far was pointing me towards some sort of functional system and I guess it's time I figure it out.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
I'm in a unique position to transition out frontend JavaScript to typescript, should I?

Roadie
Jun 30, 2013

porksmash posted:

I am indeed doing it all client side. My research so far was pointing me towards some sort of functional system and I guess it's time I figure it out.

If you've done anything with composing HOCs for React or composing reducers for Redux it's basically the same idea. The fp version turns each
JavaScript code:
whateverFunction(thingYerDoinItOn, otherOption1, otherOption2)
into
JavaScript code:
whateverFunction(otherOption1, otherOption2)(thingYerDoinItOn)
which you can then combine using flow:
JavaScript code:
const whateverFunctionsReusable = flow(
  whateverFunction(otherOption1, otherOption2),
  whateverFunction(otherOption1, otherOption2),
  whateverFunction(otherOption1, otherOption2),
)

whateverFunctionsReusable(thingYerDoinItOn)
The in-progress proposal of the pipeline operator should simplify this kind of thing further in the future by removing the need for a flow/compose function:

JavaScript code:
whateverFunctionsReusable = (thingYerDoinItOn) => thingYerDoinItOn
  |> whateverFunction(otherOption1, otherOption2)
  |> whateverFunction(otherOption1, otherOption2)
  |> whateverFunction(otherOption1, otherOption2)

whateverFunctionsReusable(thingYerDoinItOn)

Knifegrab posted:

I'm in a unique position to transition out frontend JavaScript to typescript, should I?

Absolutely.

Roadie fucked around with this message at 22:43 on Apr 20, 2018

Sedro
Dec 31, 2008

Munkeymon posted:

Is there a good way to share Tampermonkey scripts in a small group? I made one to stuff data in a UI in an internal application I had to test a lot over the last couple weeks and I figure others around here might benefit, but I don't want to distribute it outside the office.

Toss them onto a file server?

geeves
Sep 16, 2004

Munkeymon posted:

Is there a good way to share Tampermonkey scripts in a small group? I made one to stuff data in a UI in an internal application I had to test a lot over the last couple weeks and I figure others around here might benefit, but I don't want to distribute it outside the office.

I write grease/tampermonkey for my team and just store them in an /etc directory in our repo. I put a lot more into that directory than just tampermonkey scripts. I write a lot of shell scripts and python scripts to help with data setup, etc.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Man, WebGL is hosed up on phones.

Osmosisch posted:

My eyes just start kind of glazing over at that layout, sorry.

At great cost to my sanity I eventually was able to narrow down the problem myself through trial and error, each time re-uploading my website and trying it again on a phone. I commented out my shaders and replaced them with the simplest possible ones. The plan was to gradually uncomment out my real shaders until it broke but I was surprised to find that it broke down as soon as I started, at my variable declarations at the very top. Eventually I got the linker to fail with a shader that's just

code:
varying lowp float t_1;
varying lowp float t_2;
varying lowp float t_3;
varying lowp float t_4;
varying lowp float t_5;
varying lowp float t_6;
varying lowp float t_7;
varying lowp float t_8;
varying lowp float t_9;
...
33 varyings was the limit; it didn't crash at 32.

So there's a limit that's quite low on how many variables you can pass between the two shaders, and I was actually hitting that limit on phones, which was silently failing due to getProgramInfoLog not working at all on iOS.

I tested getProgramInfoLog with every type of linker error I could think to generate and they all returned an empty string for the linker error, only on phones. Is this a bug that's worth my reporting to WebKit or could I be wrong? Their bugzilla tracker looks pretty serious and I'm sure they don't want to get inundated with false positives.

Anyway it turned out one of the varyings in my program did not even need to exist. It was being used for a local temp in the vertex shader that I did not even pass on to the fragment shader. Changing it to a local fixed my whole library on phones. :cripes:

Happy Thread fucked around with this message at 01:35 on Apr 21, 2018

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
WebGL is a shithole crapshoot everywhere, but especially on WebKit. You can check the varying limit yourself with gl.getParameter(gl.MAX_VARYING_VECTORS). Explicitly pack your varyings into vec4's if you do not trust the driver implementation to do it for you. Good luck.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
The varying limit seems to be out of genuine technical need and OK, since interpolating from arbitrary indices of potentially large buffers is a challenge. I just didn't know about it.

But I'm more talking about the fact that the built-in function that's specifically for asking the graphics card if linking worked OK does not do anything on WebKit besides return empty strings. Should I report that to them or could I be wasting their time?

I've already reported one bug to them on their Bugzilla that I keep updating with my findings, and explaining reasons for why it's a terrible bug that keeps anyone from doing vector math easily in JavaScript, but they haven't touched it ever besides CC'ing 3 people.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
You seem to be under the false impression that 1) compiler errors are a requirement, 2) apple gives a poo poo about WebGL, 3) apple gives a poo poo about OpenGL drivers, 4) apple gives a poo poo about the web

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
So I am converting a project over to typescript. I am actaully poo poo at typescript but its time I learned. So far I have a pretty good grasp on things but here is somethign I don't understand:

Why in typescript can I sometimes leave off a return type in a function. I have enabled noImplicitAny and noImplicitReturns but I can still omit a return type on a function and it seems hunky dory, you would think this would be configurable or at least throw a warning. I.e.:

code:
(val: string) => { doSomething(val)}
Totally works.

But I would think I would HAVE to say:

code:
(val: string): void => { doSomething(val)}
But I don't. Isn't this overt specificity what makes typescript cool and good?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
It can infer the return type based on the body of the function. It knows that since you never returned anything, that the function returns void.

lunar detritus
May 6, 2009


I think void (and any) are not included in the noImplicitReturns by design, it should complain about everything else.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Suspicious Dish posted:

It can infer the return type based on the body of the function. It knows that since you never returned anything, that the function returns void.

No I know it can do that, but I don't understand why. I thought typescript was about sanity and clarity and having the return type with the definition seems like it would seriously help readability. Is there a way to force return type declaration or disallow inferred return type?

gmq posted:

I think void (and any) are not included in the noImplicitReturns by design, it should complain about everything else.

NoImplicitreturns just refers to explicitly returning in every switch or branch of the function, it does not relate to the type returned.

Sedro
Dec 31, 2008

Knifegrab posted:

No I know it can do that, but I don't understand why. I thought typescript was about sanity and clarity and having the return type with the definition seems like it would seriously help readability. Is there a way to force return type declaration or disallow inferred return type?

Typescript is about correctness. If you want to force unnecessary return type declarations you can use tslint or another linter.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Knifegrab posted:

No I know it can do that, but I don't understand why. I thought typescript was about sanity and clarity and having the return type with the definition seems like it would seriously help readability. Is there a way to force return type declaration or disallow inferred return type?


NoImplicitreturns just refers to explicitly returning in every switch or branch of the function, it does not relate to the type returned.

Why would you want to turn off type inference? It's a super awesome feature. One of TypeScripts strengths is that it is a superset to JavaScript, not a different language like CoffeeScript. You can adopt types as much or as little as you'd like. If you want to be explicit in your return types, you may. If you want to make suggestions as to coding standards, you could install TSLint and make it complain about this, and VSCode integrates well with it.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Skandranon posted:

Why would you want to turn off type inference? It's a super awesome feature. One of TypeScripts strengths is that it is a superset to JavaScript, not a different language like CoffeeScript. You can adopt types as much or as little as you'd like. If you want to be explicit in your return types, you may. If you want to make suggestions as to coding standards, you could install TSLint and make it complain about this, and VSCode integrates well with it.

I spent a lot of time today trying to get it working but unfortunately there is some conflict with my eslint-vue-rules plugin. Tslinter throws up when my Vue object's properties are not in alphabetical order but if I do that my eslint-vue-rules throws up because it expects a specific non alphabetical order...

Ugh this is really a pain getting typescript and Vue configured how I want...

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Skandranon posted:

Why would you want to turn off type inference? It's a super awesome feature. One of TypeScripts strengths is that it is a superset to JavaScript, not a different language like CoffeeScript. You can adopt types as much or as little as you'd like. If you want to be explicit in your return types, you may. If you want to make suggestions as to coding standards, you could install TSLint and make it complain about this, and VSCode integrates well with it.

I don't disagree but the ts compiler options has things like strict which disable implicit any which is similar in philosophy to what I'm after

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Sedro posted:

Toss them onto a file server?

geeves posted:

I write grease/tampermonkey for my team and just store them in an /etc directory in our repo. I put a lot more into that directory than just tampermonkey scripts. I write a lot of shell scripts and python scripts to help with data setup, etc.

We have a place to check stuff like this in, but I was hoping for a way that will auto-update when I have a fix or feature addition.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
I have a typescript question. I am migrating a large JS project to typescript but for a while both JS files and TS files will exist together, it is too much work to move everything ot typescript in one go.

So, I have a JS file that is effectively an API. It exports a default instance of itself that can be used to access the various API methods. These methods utilize axios to make XHR request. Axios provides pretty robust type support with its definitions file. However we are applying an interceptor that changes how the data is returned on a successful request.

This change is obviously not picked up in the typing, so when importing this file my editor and compiler expects an API request to return an AxiosResponse<any> type, however what is actually is returning is purely the data which can be of any type.

For legacy reasons I cannot edit the API js file at all. All I am trying to do is modify the type that this API uses. I want to keep all of the normal Axios type definitions because they are all appropraite an accurate and just change this one part of the type defintions. I have tried to do it in a .d.ts file but it failed, and I also didn't really know what I am doing.

I know how to specify an interface, and i know how to type things, but I cannot figure out how to modify or alter the type of an already existing thing to just override a specific part of its definition.

Any help greatly appreciated.

Sedro
Dec 31, 2008

Munkeymon posted:

We have a place to check stuff like this in, but I was hoping for a way that will auto-update when I have a fix or feature addition.

My guess is the auto-update polls the URL periodically. So a basic Apache directory listing should work.

Sedro
Dec 31, 2008

Knifegrab posted:

I have a typescript question. I am migrating a large JS project to typescript but for a while both JS files and TS files will exist together, it is too much work to move everything ot typescript in one go.

So, I have a JS file that is effectively an API. It exports a default instance of itself that can be used to access the various API methods. These methods utilize axios to make XHR request. Axios provides pretty robust type support with its definitions file. However we are applying an interceptor that changes how the data is returned on a successful request.

This change is obviously not picked up in the typing, so when importing this file my editor and compiler expects an API request to return an AxiosResponse<any> type, however what is actually is returning is purely the data which can be of any type.

For legacy reasons I cannot edit the API js file at all. All I am trying to do is modify the type that this API uses. I want to keep all of the normal Axios type definitions because they are all appropraite an accurate and just change this one part of the type defintions. I have tried to do it in a .d.ts file but it failed, and I also didn't really know what I am doing.

I know how to specify an interface, and i know how to type things, but I cannot figure out how to modify or alter the type of an already existing thing to just override a specific part of its definition.

Any help greatly appreciated.

You can use declaration merging to modify existing types. There's some limitations: it only works for certain types, the types have to be exported, etc. It's a big topic.

You could also convert everything to typescript and make compiler errors into warnings with noEmitOnError.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Sedro posted:

You can use declaration merging to modify existing types. There's some limitations: it only works for certain types, the types have to be exported, etc. It's a big topic.

You could also convert everything to typescript and make compiler errors into warnings with noEmitOnError.

I've tried everything I can as it pertains to this article, and other things I have found online but nothing works.

I have a JS file that utilizes axios:

code:
import axios from 'axios';

//this is simplified but this is effectively what it does
function checkStatus(response) {
  return response.data;
}

class APIClient {
  constructor() {
    this.client = axios.create({
    });
    this.client.interceptors.response.use(checkStatus, errorLogger); //this effectively changes the returned type when the axios promise resolves
  }
  getThing() {
    return this.client.get('thing');
  }
}


const instance = new APIClient();
Object.freeze(instance);
export default instance;

(This file cannot be altered for legacy reasons)
Now because this file uses axios when I imported this file it assumes all of axios's types. However the interceptor logic there fucks it all up and the returned typed from a request isn't actually an AxiosResponse but instead just data.

so in my TS file where I import the API script:

code:

import API from '../../api';

...

  API.getThing()
  .then(data => { ... });

But typescript expects 'data' in this case to be an AxiosResponse and not just a value of type any. So I have tried creating a wrapper file:

code:

import api from './index';

import { AxiosInterceptorManager, AxiosStatic } from 'axios';

declare module './index' {
  interface AxiosStatic {
    interceptors: {
      response: AxiosInterceptorManager<any>;
    };
  }
}

export default api;
And importing that but it did not work at all.

I am really confused, I cannot seem to declare a module type at the top of my file either it throws an error.

Any help is seriously appreciated, I am banging my head against a wall and without a fix no progress can be made on this conversion.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Knifegrab posted:

I've tried everything I can as it pertains to this article, and other things I have found online but nothing works.

I am really confused, I cannot seem to declare a module type at the top of my file either it throws an error.

Any help is seriously appreciated, I am banging my head against a wall and without a fix no progress can be made on this conversion.

Have you tried writing a d.ts file which explicitly defines your APIClient the way you want?

code:
    class APIClient  {
        constructor();
        getThing(): () => IMyInterfaceNotInferedType;
        getThing2(): (param: string) => IMyInterfaceNotInferedType2;
    }

Skandranon fucked around with this message at 05:43 on Apr 24, 2018

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Skandranon posted:

Have you tried writing a d.ts file which explicitly defines your APIClient the way you want?

code:
    class APIClient  {
        constructor();
        getThing(): () => IMyInterfaceNotInferedType;
        getThing2(): (param: string) => IMyInterfaceNotInferedType2;
    }

So oddly enough I tried this but then when I try to import my original file it for some reason thinks I am just importing the type defintions and I cannot use any of my API methods... maybe a namespace conflict? This is all so confusing.

For clarity, after writing the .d.ts how would I then slap that definition onto my API object?

Knifegrab fucked around with this message at 06:52 on Apr 24, 2018

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Sedro posted:

My guess is the auto-update polls the URL periodically. So a basic Apache directory listing should work.

:doh: I just noticed that Update URL field.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Knifegrab posted:

So oddly enough I tried this but then when I try to import my original file it for some reason thinks I am just importing the type defintions and I cannot use any of my API methods... maybe a namespace conflict? This is all so confusing.

For clarity, after writing the .d.ts how would I then slap that definition onto my API object?

VSCode should pick up the d.ts file automatically if it is in your project, and should provide intellisense based on that. For compilation, you'll need to tell the compiler to include it. If the names match, the definitions from the d.ts should be taken over any inferred types from the source files.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Skandranon posted:

VSCode should pick up the d.ts file automatically if it is in your project, and should provide intellisense based on that. For compilation, you'll need to tell the compiler to include it. If the names match, the definitions from the d.ts should be taken over any inferred types from the source files.

So the name of the .d.ts file has to be same as the file I am supplying types for? Does the name of the class have to be the same as well? Also what would the class actually look like, and am I exporting the class in the .d.ts or merely declaring it?

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Knifegrab posted:

So the name of the .d.ts file has to be same as the file I am supplying types for? Does the name of the class have to be the same as well? Also what would the class actually look like, and am I exporting the class in the .d.ts or merely declaring it?

Filename should not matter. Name of class should be the same. You write the interface for how you want TypeScript to handle your APIClient class. Should just be declaring it.

Sedro
Dec 31, 2008
It's an ES6 module so the filename does matter. If the JS file is client.js then it should be named client.d.ts.

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Sedro posted:

It's an ES6 module so the filename does matter. If the JS file is client.js then it should be named client.d.ts.

Depends how it's being distributed. If he's making a d.ts for this module to be distributed with it, sure, though the package.json can point to any file as it's main typing file. If he's simply adding typings to some external library in his project, the filename does not matter.

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe
I'm trying to find and remove duplicates in an array. The array would have an item name and item code like:
code:
[[item1,9090],[item2,9090],[item3,9010]]
I found a code that would go through the array and push out unique value, but I don't fully understand how it works.

code:
function removeDuplicate(arr){
     var i,
  len=arr.length,
  result = [],
  obj = {}; 
  for (i=0; i<len; i++)
  {
  obj[arr[i][1]]=0;
  }
  for (i in obj) {
  result.push(i);
  }
  return result;
  }
I changed the
code:
obj[arr[i]]=0;
to
code:
obj[arr[i][1]]=0;
so it will filter based on unique item code for my array above.
The code itself seem to do the job in filtering, but how would I modify the code so it will also push the item name? So ideally the result would be:
code:
[[item1,9090],[item3,9010]]

Cugel the Clever
Apr 5, 2009
I LOVE AMERICA AND CAPITALISM DESPITE BEING POOR AS FUCK. I WILL NEVER RETIRE BUT HERE'S ANOTHER 200$ FOR UKRAINE, SLAVA
I adore Typescript, but the official documentation for writing definitions is impossible to parse for me. I've gotten to the point where I can draft up definitions for a third-party library and have it work fine, but have only arrived at this point through a whole lot of trial, error, and cribbing off random definitions from DefinitelyTyped. A lot of the upvoted answers on Stackoverflow are just recommendations to use a @ts-ignore or coerce the offending file to any...

Has anyone come across a solid resource that makes everything just click?

Cugel the Clever fucked around with this message at 00:00 on Apr 29, 2018

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Revalis Enai posted:

I'm trying to find and remove duplicates in an array. The array would have an item name and item code like:
code:
[[item1,9090],[item2,9090],[item3,9010]]
I found a code that would go through the array and push out unique value, but I don't fully understand how it works.

code:
function removeDuplicate(arr){
     var i,
  len=arr.length,
  result = [],
  obj = {}; 
  for (i=0; i<len; i++)
  {
  obj[arr[i][1]]=0;
  }
  for (i in obj) {
  result.push(i);
  }
  return result;
  }
I changed the
code:
obj[arr[i]]=0;
to
code:
obj[arr[i][1]]=0;
so it will filter based on unique item code for my array above.
The code itself seem to do the job in filtering, but how would I modify the code so it will also push the item name? So ideally the result would be:
code:
[[item1,9090],[item3,9010]]

The way the original code is de-duplicating is that it's putting all the objects into an associative array as keys, and since you can't have duplicate values in an associate array - voila, the stuff is de-duplicated.

However, it's not great for objects because you're only de-duplicating the key names.

A better way of de-duplicating is to use Array.filter... e.g.

code:
function unique(a) {
    var seen = {};
    return a.filter(function(item) {
        var k = item[1];
        return seen.hasOwnProperty(k) ? false : (seen[k] = true);
    })
}
Array.filter runs a test on every object in an array - if the test returns true, then the object is returned. This will return [[item1,9090],[item3,9010]]

Bruegels Fuckbooks fucked around with this message at 00:07 on Apr 29, 2018

Roadie
Jun 30, 2013
The actual thing to do when deduplicating an array is to just use the Lodash version, since they've already done all the work and it's guaranteed to be more correct than whatever you can come up with in a reasonable amount of time.

JavaScript code:
import uniqBy from 'lodash.uniqby'

const initialArray = [[item1, 9090], [item2, 9090], [item3, 9010]]
const result = uniqBy(initialArray, item => item[1])
For conceptually straightforward transformations on arrays and plain objects, looking for a Lodash method before rolling your own is always a good idea, because they're already covered a ton of this stuff.

Sergeant Rock
Apr 28, 2002

"... call the expert at kissing and stuff..."
If you are allowed to use ES6, you can use a Set to really easily dedupe:

let oldarr = ['blah', 'boing', 'blah'];

let deduped = [...new Set(oldarr)];

Adbot
ADBOT LOVES YOU

Revalis Enai
Apr 21, 2003
<img src="https://fi.somethingawful.com/customtitles/title-revalis_enai.gif"><br>Wait, what's my phone number again?
Fun Shoe

Bruegels Fuckbooks posted:

The way the original code is de-duplicating is that it's putting all the objects into an associative array as keys, and since you can't have duplicate values in an associate array - voila, the stuff is de-duplicated.

However, it's not great for objects because you're only de-duplicating the key names.

A better way of de-duplicating is to use Array.filter... e.g.

code:
function unique(a) {
    var seen = {};
    return a.filter(function(item) {
        var k = item[1];
        return seen.hasOwnProperty(k) ? false : (seen[k] = true);
    })
}
Array.filter runs a test on every object in an array - if the test returns true, then the object is returned. This will return [[item1,9090],[item3,9010]]

Wow, the code got exactly what I was looking for and it ran fast. I'm trying to figure out how it actually does the filtering. From what I understand it's going through every item code(item[1]) to see if the object has its own property? If true, then it's set to false, and if false, it does (seen[k] =true), which I'm not sure what that does.

quote:

The actual thing to do when deduplicating an array is to just use the Lodash version, since they've already done all the work and it's guaranteed to be more correct than whatever you can come up with in a reasonable amount of time.

Javascript code:
import uniqBy from 'lodash.uniqby'

const initialArray = [[item1, 9090], [item2, 9090], [item3, 9010]]
const result = uniqBy(initialArray, item => item[1])
For conceptually straightforward transformations on arrays and plain objects, looking for a Lodash method before rolling your own is always a good idea, because they're already covered a ton of this stuff.

This looks interesting, but I don't think I'm able to utilize it since I work mostly with Google Apps Script, and apparently using libraries can be slow.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply