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
necrotic
Aug 2, 2005
I owe my brother big time for this!
If that answer was given to me in an interview you wouldn't get the job. But yeah js is terrible

Adbot
ADBOT LOVES YOU

ROFLburger
Jan 12, 2006

Grump posted:

God i just took a coding test for an interview and i'm only realizing now comparing two arrays is such a pain in JS

Just curious could you be more specific? I can't think of why this would be unless you're talking about equality comparisons when you're looping through?

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
I'm curious about the actual question and how it was worded. I can think of a few ways, but I'm still learning JS, so it would be a fun exercise for me...

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
So basically i'm converting a array of ints into a multidimensional array with pairs that add up to 10.

Then i had to filter out the duplicates and that's where i was running into trouble with comparing the nested arrays. Converting them to strings works fine as far as i'm concerned

code:

//Write a program that allows for an integer array to be passed in and will then output all of the pairs that sum up to 10.  
//Please provide a solution that allows for 1) output all pairs (includes duplicates and the reversed ordered pairs), 
//2) output unique pairs only once (removes the duplicates but includes the reversed ordered pairs), 
//and 3) output the same combo pair only once (removes the reversed ordered pairs). 

//find pairs of ints that add to 10
const pairsSumToTen = function getPairs(arrayOfInts) { //takes an array of ints as an argument
    let result = []; //used for every pair of numbers that add to ten

    for (i = 0; i < arrayOfInts.length; i++) { //map over the array
        let arrayWithoutIndex = arrayOfInts.filter(function (element, index) {
            return index != i;
        }); //make a new array but filter out the index
        for (k = 0; k < arrayWithoutIndex.length; k++) { //then map over that array and compare the index to every other int
            if (arrayOfInts[i] + arrayWithoutIndex[k] === 10) { //if the two values add to 10, make an array with those two ints
                result.push([arrayOfInts[i], arrayWithoutIndex[k]]);
            }
        }
    }
    return result;
}

// remove all duplicates from the mutlidimensional array. Disregard reverse
// order matches
const getUniquePairs = function uniquePairs(arrayOfPairs) { //takes an multidimensional array of ints
    arrayOfPairs.sort(); //first, let's sort the array so it's simpler to compare each element
    let result = [];
    for (let i = 0; i < arrayOfPairs.length - 1; i++) { //map over every element except the last
        if (arrayOfPairs[i].join('') !== arrayOfPairs[i + 1].join('')) { //turn the arrays into strings and compare them that way. Using JSON.stringify is poor practice
            result.push(arrayOfPairs[i]);
        }
    }
    let lastElement = arrayOfPairs.pop(); //the last element in the array is always going to be unique, so always push it to the result array
    result.push(lastElement);
    return result;
}

// remove all duplicates from multidimensional array - even the reverse order
// pairs
const getReverseOrderPairs = function reverseOrder(array) {
    let sortedElements = array.map(function (value, index, array) {
        return value.sort(); //sort each element in the array so it's easier to filter later
    })
    sortedElements.sort(); //then sort the outer-most array
    let result = getUniquePairs(sortedElements); //since they're already sorted, all we have to do is get rid of the unique pairs
    return result;
}

//TEST CASES:

console.log(pairsSumToTen([
    1,
    1,
    2,
    4,
    4,
    5,
    5,
    5,
    6,
    7,
    9
])); //result: [[1, 9], [1, 9], [4, 6], [4, 6], [5, 5], [5, 5], [5, 5], [5, 5], [5, 5], [5, 5], [6, 4], [6, 4], [9, 1], [9, 1]]
console.log(getUniquePairs(pairsSumToTen([
    1,
    1,
    2,
    4,
    4,
    5,
    5,
    5,
    6,
    7,
    9
]))); //result: [[1, 9], [4, 6], [5, 5], [6, 4], [9, 1]]
console.log(getReverseOrderPairs(pairsSumToTen([
    1,
    1,
    2,
    4,
    4,
    5,
    5,
    5,
    6,
    7,
    9
]))); //result: [[1, 9], [4, 6], [5, 5]]

console.log(pairsSumToTen([
    0,
    1,
    2,
    3,
    5,
    7,
    10,
    3,
    5
])); //[[0, 10], [3, 7], [5, 5], [7, 3], [7, 3], [10, 0], [3, 7], [5, 5]]
console.log(getUniquePairs(pairsSumToTen([
    0,
    1,
    2,
    3,
    5,
    7,
    10,
    3,
    5
]))); //[[0, 10], [10, 0], [3, 7], [5, 5], [7, 3]]
console.log(getReverseOrderPairs(pairsSumToTen([
    0,
    1,
    2,
    3,
    5,
    7,
    10,
    3,
    5
]))); //[[0, 10], [3, 7], [5, 5]]

teen phone cutie fucked around with this message at 18:16 on Jun 16, 2017

MrMoo
Sep 14, 2000

The classic JSON.stringify(a) === JSON.stringify(b) is still valid for comparing objects. With arrays there is room for interpretation of what equality means, the Polymer project has this issue when detecting changes in an array:

https://www.polymer-project.org/1.0/docs/devguide/model-data

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
For this problem, I feel like you can just use the fact that you know you're dealing with pairs, and that the pairs add up to 10.

To get the pairs, do what you do and make the array of length 2 arrays.

You know that all the pairs add up to 10, so for each pair, any other pair that has the same first element, it's a duplicate. This won't touch reversed pairs.

Once you have stripped out duplicates, for each pair, any pair whose second element is equal to the first element of the pair you are comparing to is a reversal of that pair.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

MrMoo posted:

The classic JSON.stringify(a) === JSON.stringify(b) is still valid for comparing objects. With arrays there is room for interpretation of what equality means, the Polymer project has this issue when detecting changes in an array:

https://www.polymer-project.org/1.0/docs/devguide/model-data

I was gonna use json.stringify but everybody on stackoverflow was crucifying it since it's slow.

MrMoo
Sep 14, 2000

Made me remember this:

https://twitter.com/ID_AA_Carmack/status/844885670732685313

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
Here's the implementation of my suggestion

code:
/*Write a program that allows for an integer array to be passed in and will then output all of the pairs that sum up to 10. Please provide a solution that allows for 
1) output all pairs (includes duplicates and the reversed ordered pairs) 
2) output unique pairs only once (removes the duplicates but includes the reversed ordered pairs) 
3) output the same combo pair only once (removes the reversed ordered pairs) 
*/

var testArray = [ 1, 1, 2, 4, 4, 5, 5, 5, 6, 7, 9];

function pairsSumToTen(inputArray){
	let result = [];
  
  	for (i = 0; i < inputArray.length; i++){
  		for (j = 0; j < inputArray.length; j++){
    			if (i != j && inputArray[i] + inputArray[j] == 10){
        			result.push([inputArray[i], inputArray[j]]);
      			}
    		}
  	}
	return result;
}

function removeDuplicates(pairArray){
	let result = [];

	if (pairArray.length < 2){
  		return pairArray;
  	}
  
  	for (i = 0; i < pairArray.length; i++){
  		var hasDupe = false;
  		
		for (j = i+1; j < pairArray.length; j++){
    			if (i != j && pairArray[i][0] == pairArray[j][0]){
        			hasDupe = true;
        			break;
      			} 
    		}
    
		if (!hasDupe){
    			result.push(pairArray[i]);
    		}
  	}
  	return result;
}

function removeReversed(pairArray){
	let result = [];
  
	if (pairArray.length < 2){
  		return pairArray;
  	}
  
  	for (i = 0; i < pairArray.length; i++){
  		var hasDupe = false;
  	
		for (j = i+1; j < pairArray.length; j++){
    			if (i != j && pairArray[i][0] == pairArray[j][1]){
        			hasDupe = true;
        			break;
      			} 
    		}
    
		if (!hasDupe){
    			result.push(pairArray[i]);
    		}
  	}
  	return result;
}

var output = pairsSumToTen(testArray);
var noDupe = removeDuplicates(output);
var noRev = removeReversed(noDupe);

console.log(output.join('\n'));
console.log(noDupe.join('\n'));
console.log(noRev.join('\n'));
I'm not sure it's better that yours in any way, but it doesn't use any conversion to strings.

It's here in jfiddle if anyone wants to play with it. https://jsfiddle.net/352na4gd/1/
Like I said, I'm just learning JS, so if I didn't any real bad, please point it out. Thanks.

edit: My spaces were converted to tabs when I pasted it here? or something?

necrotic
Aug 2, 2005
I owe my brother big time for this!
If you use tab in jsfiddle it's actually putting in tabs, but displays as 4? 2? spaces visually.

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
That explains the confusion. Partially. I used only tabs when in jsfiddle, but when I pasted it, it was a mix of tabs and spaces, so I don't even know.

hooah
Feb 6, 2006
WTF?

Love Stole the Day posted:

I really liked Ben Fhala's thing on Packt, which served as my intro to React. You can do their "1 month free trial"for the Mapt thing so that you can access it and all their other React stuff for free until the trial thing is up. I've been using it to cram with all sorts of stuff and it'll finish in 5 days.

So where do I get the starting project for React now? The website's different than the starting video and the closest thing I can find on Facebook's github is the create-react-app repo which has a completely different project structure than what Ben's working with.

The Fool
Oct 16, 2003


Welcome to react

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

The Fool posted:

Welcome to react

It's more like "welcome to tutorials on the internet". Things change and a tutorial not developed to take that into account is not being the best it can be. Granted, JS stuff changes a lot nowadays, but that puts even more of an onus on teaching material.

ddiddles
Oct 21, 2008

Roses are red, violets are blue, I'm a schizophrenic and so am I
Thats why whenever I search for tutorials on google, I set the search range to only show stuff from the past three months.

Even then, sometimes whatever package they are using has completely changed in that time frame.

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
The worst are tutorials that don't say what version they are for.

TopherCStone
Feb 27, 2013

I am very important and deserve your attention
Is there a Javascript library suited for creating print-ready images?

I need to create an image with a lot of repeated elements, specifically 40 half-inch squares with some text centered vertically and horizontally in each. I'd rather not do all of this manually in an image editor, and ideally I could rig up a few inputs so I can vary things and get a live preview before saving and printing the file. I've looked at a few SVG libraries, but I'm not sure if that's the best approach.

e: one important thing is being able to get the text centered based on the text's bounding box, not the baseline.

TopherCStone fucked around with this message at 21:08 on Jun 17, 2017

Dominoes
Sep 20, 2007

Hey dudes. Looking for API feedback on the datetime module I've been working on. And a re-attack on why I can't get it to import as an npm module (But can by placing the source file in the same folder as my project). I've decided to de-couple it from DateFns, since I'm unable to get around it not accepting these custom types as valid when using certain funcs, as well as API limitations I hadn't noticed with it earlier. (ie it's impossible to safely turn a string into a date with that module).

I'd also like to verify that I'm not alone in thinking not having separate date, time, datetime, and delta types is absurd.

Dominoes fucked around with this message at 00:38 on Jun 18, 2017

Dreadrush
Dec 29, 2008

Grump posted:

God i just took a coding test for an interview and i'm only realizing now comparing two arrays is such a pain in JS

I just turned them into strings and compared them that way but not sure if there's a better way :shrug:

When comparing two arrays I usually use lodash's isEqual function:
code:
_.isEqual([0, 1], [0, 1]); // true

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

Dreadrush posted:

When comparing two arrays I usually use lodash's isEqual function:
code:
_.isEqual([0, 1], [0, 1]); // true

Yes, that's a cute answer. I'd then ask you to write out _.isEqual().

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
Yeah i don't really get why i'm getting crucified. My answer works so who cares???

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
No one's crucifying you? Your answer is good...

Dominoes
Sep 20, 2007

Skandranon posted:

Yes, that's a cute answer. I'd then ask you to write out _.isEqual().
Even with ES2015, Lodash can be treated as a built-in part of palatable Javascript!

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

Grump posted:

Yeah i don't really get why i'm getting crucified. My answer works so who cares???

Sorry, that was not my intent. I was more attacking the idea of answering such questions with library calls. The point of asking "do a sort" or "compare this" is to work through it. Calling "Superlib.doAnything()", while a practical thing to do while actually programming, is not the point of the question.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Dominoes posted:

Hey dudes. Looking for API feedback on the datetime module I've been working on. And a re-attack on why I can't get it to import as an npm module (But can by placing the source file in the same folder as my project). I've decided to de-couple it from DateFns, since I'm unable to get around it not accepting these custom types as valid when using certain funcs, as well as API limitations I hadn't noticed with it earlier. (ie it's impossible to safely turn a string into a date with that module).

I'd also like to verify that I'm not alone in thinking not having separate date, time, datetime, and delta types is absurd.

It's not clear to me what (if anything) webpack is adding to the build process here. Running the typescript compiler in the root directory will read your tsconfig file and follow those instructions. I've recently been over the hump of publishing a TS project to npm, and I don't see any immediate reason why this one shouldn't be working (if your build is running and your /dist folder gets populated with index.js and index.d.ts).

e: I submitted a pull request, why not. Feel free to reject it, I mostly wanted to push some new buttons. As it stands I was able to npm install it from my local directory.

Newf fucked around with this message at 06:53 on Jun 18, 2017

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Skandranon posted:

Sorry, that was not my intent. I was more attacking the idea of answering such questions with library calls. The point of asking "do a sort" or "compare this" is to work through it. Calling "Superlib.doAnything()", while a practical thing to do while actually programming, is not the point of the question.

Yeah, well the obvious reason you want the implementation as an interviewer is to verify the candidate:

- knows which variables are compared by reference vs value
- knows how to determine whether you have an object or an array, and how to compare said arrays and objects.

Delving implementation indicates you understand fully why lodash has isEquals, which makes it clear you understand some basic facts about how JavaScript treats values.

Dreadrush
Dec 29, 2008

Skandranon posted:

Yes, that's a cute answer. I'd then ask you to write out _.isEqual().

I'd then tell you that you and I are not in an interview and I'm merely giving someone an alternative solution when they come across the problem again.

necrotic
Aug 2, 2005
I owe my brother big time for this!
The entire conversation is about an interview question.

Dominoes
Sep 20, 2007

Newf posted:

It's not clear to me what (if anything) webpack is adding to the build process here. Running the typescript compiler in the root directory will read your tsconfig file and follow those instructions. I've recently been over the hump of publishing a TS project to npm, and I don't see any immediate reason why this one shouldn't be working (if your build is running and your /dist folder gets populated with index.js and index.d.ts).

e: I submitted a pull request, why not. Feel free to reject it, I mostly wanted to push some new buttons. As it stands I was able to npm install it from my local directory.
You did it! Merged your pull, and now it works. Now if only TSC would offer bundling/imports, we could forget about webpack entirely.

Dominoes fucked around with this message at 15:46 on Jun 18, 2017

9-Volt Assault
Jan 27, 2007

Beter twee tetten in de hand dan tien op de vlucht.

Skandranon posted:

Yes, that's a cute answer. I'd then ask you to write out _.isEqual().

Lol if you expect your developers to copy existing functionality for the sake of it.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Dominoes posted:

You did it! Merged your pull, and now it works. Now if only TSC would offer bundling/imports, we could forget about webpack entirely.

What is it that you mean by bundling / imports? TSC is using your imported date-fns library here. The 'outfile' flag on compiler options in your tsconfig.json can be used to specify a concatenated, single-file compiled js output, but that's moot in the current case, since your package only has one source file to begin with.

Dominoes
Sep 20, 2007

Newf posted:

What is it that you mean by bundling / imports? TSC is using your imported date-fns library here. The 'outfile' flag on compiler options in your tsconfig.json can be used to specify a concatenated, single-file compiled js output, but that's moot in the current case, since your package only has one source file to begin with.
To clarify: As you've demonstrated, tsc alone works great for this project, but not for projects that need to import other modules; otherwise it's script tags. I suspect most full websites land in this category. Ie, this is how Typescript explicitly tells you to set it up: official guide. I'm I'm wrong, I'd love to know, but I've found no way to make import syntax work without webpack.

It sound slike from your 'outfile' comment that I'm wrong... I'm skeptical because I spent a good deal of time trying to get imports working with tsc alone, and failed / people on the internet told me I couldn't. How would you set up the equiv of this: ? Ie different scripts for different pages:

From webpack.config.js
JavaScript code:
module.exports = {
    entry: {
        schedule: "./pucks/static/src/schedule.tsx",
        week_schedule: "./pucks/static/src/week_schedule.tsx",
        quals: "./pucks/static/src/quals.ts",
        inputs: "./pucks/static/src/inputs.ts",
        ground_training: "./pucks/static/src/ground_training.ts",
        upgrades: "./pucks/static/src/upgrades.ts",
        rap: "./pucks/static/src/rap.ts",
        me: "./pucks/static/src/me.ts"
    },
    output: {
        filename: "[name].js",
        path: __dirname + "/pucks/static/dist"
    },

Dominoes fucked around with this message at 19:02 on Jun 18, 2017

qsvui
Aug 23, 2003
some crazy thing

9-Volt Assault posted:

Lol if you expect your developers to copy existing functionality for the sake of it.

necrotic posted:

The entire conversation is about an interview question.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Exactly, reimplementing isEqual is a great interview question for establishing whether someone knows basic facts about JavaScript equality and how to rigorously test it properly. . If that's the level of knowledge you'd like it makes sense as a question, and hardly fits within the realm of an ugly or excessive trick question.

Dominoes
Sep 20, 2007

Is the trick to iterate over each element and comparing with ==, and recursively if the element's an array?

Any plans in the next ES version to make array1 == array2 work? Why doesn't it in existing versions?

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

Dominoes posted:

Is the trick to iterate over each element and comparing with ==, and recursively if the element's an array?

Any plans in the next ES version to make array1 == array2 work? Why doesn't it in existing versions?

The problem with this is that == and === only compare values for primitive types (string, number, boolean). However, if you have 2 objects that have identical contents (ie: { "name": "Skandranon", "age": 9000 } === { "name": "Skandranon", "age": 9000 }) will be false, as when === is used for objects, it is only comparing the memory address it points at, basically seeing if they are LITERALLY the same object, not if they are equivalent. So for objects you need to recursively iterate over all properties and check that their names & values are the same.

Dominoes
Sep 20, 2007

JS is an evolving language; no excuse for comparing the arrays directly not to work.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Dominoes posted:

JS is an evolving language; no excuse for comparing the arrays directly not to work.

How do you propose to implement that without breaking all the code that depends on referential checks for high performance?

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

Dominoes posted:

JS is an evolving language; no excuse for comparing the arrays directly not to work.

You can complain about JavaScript, or write web applications in some other language (good luck with that). Learn to love the one you are with.

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

Maluco Marinero posted:

How do you propose to implement that without breaking all the code that depends on referential checks for high performance?
New JS versions already compile down to existing JS; just have the transpiler interpret array1 == array2 as whatever verbose syntax you currently need to use. Code bases that rely on the current comparison behavior can skip the new language/transpiler.

Skandranon posted:

Learn to love the one you are with.
SyntaxError: not a chance

Dominoes fucked around with this message at 01:06 on Jun 19, 2017

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