DEV Community

loading...

Discussion on: Daily Challenge #273 - Remove Duplicates

Collapse
qm3ster profile image
Mihail Malo • Edited

javascript

const solve = arr => {
  const vals = new Map()
  for (let i=0; i < arr.length; i++) vals.set(arr[i], i)
  const sparse = new Array(arr.length)
  for (const [v, i] of vals) sparse[i] = v
  const out = new Array(vals.length)
  let o = 0;
  for (const i in sparse) out[o++] = sparse[i]
  return out
}

The question remains, does the for in kill the man what if it sorts lexically and not numerically? Should I have just for (const x of sparse) if (typeof x !== "undefined") out[o++] = x?

Maybe

function * isDef(it) {
  for (const x of it) if (typeof x !== "undefined") yield x
}
const solve = arr => {
  const vals = new Map() // tfw no Map::with_capacity
  for (let i=0; i < arr.length; i++) vals.set(arr[i], i)
  const sparse = new Array(arr.length)
  for (const [v, i] of vals) sparse[i] = v
  const out = new Array(vals.length)
  const search = isDef(sparse)
  for (let i = 0; i < vals.length; i++) out[i++] = search.next()
  return out
}

ayy lmao