Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Created January 15, 2014 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghoseb/8432086 to your computer and use it in GitHub Desktop.
Save ghoseb/8432086 to your computer and use it in GitHub Desktop.
Uniquify buffer names
(ns ^{:doc "Uniquify"
:author "Baishampayan Ghose <b.ghose@helpshift.com>"}
uniquify
(:require [clojure.string :refer [join]]))
(defn explode
"Explode a directory name to its subcomponents."
[^String dir]
(seq (.split dir "/")))
(defn tails
"Successive tails of a collection."
[coll]
(when-not (empty? coll)
(cons coll (tails (rest coll)))))
(defn paths
"Given an exploded sequence, get all possible sub-paths."
[xs]
(map (partial join "/") xs))
(defn index
"Index all possible subcomponents with their counts."
[path-coll]
(reduce (fn [res p] (merge-with + res (frequencies p))) {} path-coll))
(defn uniquify
"Uniquify the string representations of all paths."
[ps]
(let [ps (map (comp paths tails explode) ps)
idx (index ps)]
(map first
(for [p (map reverse ps)]
(for [x p :when (= (idx x) 1)]
x)))))
;;; (def in ["a/b/c" "a/c/d" "a/b/d" "c/b/d" "a/c/x"])
;;; (def out ["c" "c/d" "a/b/d" "c/b/d" "x"])
;;; (uniquify in)
;;; ;=> ("c" "c/d" "a/b/d" "c/b/d" "x")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment